Compare commits

..
Author SHA1 Message Date
Phin Wolkwitz facec4fc14 Add gates to resources' index 2026-11-25 18:56:07 +01:00
pajowuandRaphael Michel a27f2db92c Store tax code in CartPosition (Z#23254725) (#6812)
* Store tax code in CartPosition (Z#23254725)

* Fix test

---------

Co-authored-by: Raphael Michel <michel@pretix.eu>
2026-11-25 17:02:01 +01:00
pajowu 5d1f4d073c Add MB WAY payment method (Z#23254887) (#6817) 2026-11-25 16:57:05 +01:00
luelista 47c7abbc7f Waiting list: Use defusedcsv for download (#6818)
* Use defusedcsv for waiting list download

* Disallow equal signs in names
2026-11-25 16:41:23 +01:00
Raphael MichelandMartin Gross a05c3d6eee API: Allow pretixPOS to communicate its binding tax calculation (#6718)
* API: Allow pretixPOS to communicate its binding tax calculation

* Fixes, fee support and total check

* Fix test on postgresql

* Fix handling of inbound prices

---------

Co-authored-by: Martin Gross <gross@pretix.eu>
2026-11-25 16:40:47 +01:00
Raphael MichelandMartin Gross 3b2cd96c6f POS settings API: Expose tax rounding mode (#6721)
Co-authored-by: Martin Gross <gross@pretix.eu>
2026-11-25 16:39:46 +01:00
Raphael Michel 3d68b7db11 Tax rounding: Allow to round by gross total (#6706) 2026-11-25 16:37:36 +01:00
pajowu 7de255d3ac Add I18nInput component (#6767)
* Add I18nInput component, cleanup i18nstring-handling
* Replace deprecated __dirname with import.meta.dirname
2026-11-25 13:31:26 +01:00
Raphael Michel c0d887738b Remove unussed LockModel (#6808) 2026-11-25 10:50:59 +01:00
luelista cc43537898 Remove some legacy code and document deprecations (#6803)
* Stripe: Remove legacy session migration code
* Remove Django 5.2 backport of simple_block_tag (we are at Django 5.2 by now)
* Word deprecation of /checkinlists/.../positions/<secret>/redeem/ more strongly
2026-11-25 10:47:48 +01:00
Richard Schreiber 40ea9097d0 Show claim_token of reusable media in control details view (#6816) 2026-11-24 14:53:18 +01:00
Richard Schreiber c3152c4eff Exclude items that require a voucher from waitinglist (#6811) 2026-11-24 08:51:49 +01:00
Raphael Michel 3906a9593d Subevent bulk editor: Allow to override unused checkin lists (Z#23253417) (#6771)
* Subevent bulk editor: Allow to override unused checkin lists (Z#23253417)

* Fix isort
2026-11-24 08:02:04 +01:00
Phin WolkwitzandRichard Schreiber 36db1134aa API: Add an endpoint for gates (Z#23239580) (#6794)
Co-authored-by: Richard Schreiber <wiffbi@gmail.com>
2026-11-23 11:28:58 +01:00
52 changed files with 1273 additions and 493 deletions

No files matched your search

+4 -4
View File
@@ -605,19 +605,19 @@ Order position endpoints
Tries to redeem an order position, identified by its internal ID, i.e. checks the attendee in. This endpoint
accepts a number of optional requests in the body.
**Tip:** Instead of an ID, you can also use the ``secret`` field as the lookup parameter. In this case, you should
always set ``untrusted_input=true`` as a query parameter to avoid security issues.
**Deprecated behavior:** For legacy compatibility, the ``secret`` field is also accepted as the lookup parameter.
Do not depend on that behaviour as it will be removed in the future, such that only the internal ID is accepted.
.. note::
We no longer recommend using this API if you're building a ticket scanning application, as it has a few design
Do not use this API to redeem tickets if you're building a ticket scanning application, as it has a few design
flaws that can lead to `security issues`_ or compatibility issues due to barcode content characters that are not
URL-safe. We recommend to use our new :ref:`check-in API <rest-checkin>` instead. Advanced features like medium
exchange are only supported on the new API.
:query boolean untrusted_input: If set to true, the lookup parameter is **always** interpreted as a ``secret``, never
as an ``id``. This should be always set if you are passing through untrusted, scanned
data to avoid guessing of ticket IDs.
data to avoid guessing of ticket IDs. (**Deprecated**, use the new :ref:`check-in API <rest-checkin>` instead)
:>json boolean questions_supported: When this parameter is set to ``true``, handling of questions is supported. If
you do not implement question handling in your user interface, you **must**
set this to ``false``. In that case, questions will just be ignored. Defaults
+195
View File
@@ -0,0 +1,195 @@
Gate resource
-------------
The gate resource contains the following public fields:
.. rst-class:: rest-resource-table
===================================== ========================== =======================================================
Field Type Description
===================================== ========================== =======================================================
id integer Internal ID of the gate within this organizer
name string gate name
identifier string Internal identifier to make it easier to match the data with other sources
===================================== ========================== =======================================================
Endpoints
----------------
.. http:get:: /api/v1/organizers/(organizer)/gates/
Returns a list of all gates within a given organizer.
**Example request**:
.. sourcecode:: http
GET /api/v1/organizers/bigevents/gates/ HTTP/1.1
Host: pretix.eu
Accept: application/json, text/javascript
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Vary: Accept
Content-Type: application/json
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": 1,
"name": "Main door",
"identifier": "west_entry"
}
]
}
:param organizer: The ``slug`` field of the organizer to fetch
:statuscode 200: no error
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer does not exist **or** you have no permission to view this resource.
.. http:get:: /api/v1/organizers/(organizer)/gates/(id)/
Returns information on one gate, identified by its ID.
**Example request**:
.. sourcecode:: http
GET /api/v1/organizers/bigevents/gates/1/ HTTP/1.1
Host: pretix.eu
Accept: application/json, text/javascript
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Vary: Accept
Content-Type: application/json
{
"id": 1,
"name": "Main door",
"identifier": "west_entry"
}
:param organizer: The ``slug`` field of the organizer to fetch
:param id: The ``id`` of the gate to fetch
:statuscode 200: no error
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer does not exist **or** you have no permission to view this resource.
.. http:post:: /api/v1/organizers/(organizer)/gates/
Creates a new gate
You can supply the following fields of the resource:
* ``name``
* ``identifier`` (optional, if you do not supply one, it will be auto-generated)
**Example request**:
.. sourcecode:: http
POST /api/v1/organizers/bigevents/gates/ HTTP/1.1
Host: pretix.eu
Accept: application/json, text/javascript
Content-Type: application/json
{
"name": "South gate",
"identifier": "south_entry",
}
**Example response**:
.. sourcecode:: http
HTTP/1.1 201 Created
Vary: Accept
Content-Type: application/json
{
"id": 2,
"name": "South gate",
"identifier": "south_entry"
}
:param organizer: The ``slug`` field of the organizer to create a gate for
:statuscode 201: no error
:statuscode 400: The gate could not be created due to invalid submitted data.
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer/gate does not exist **or** you have no permission to create this resource.
.. http:patch:: /api/v1/organizers/(organizer)/gates/(id)/
Update a gate.
**Example request**:
.. sourcecode:: http
PATCH /api/v1/organizers/bigevents/gates/1/ HTTP/1.1
Host: pretix.eu
Accept: application/json, text/javascript
Content-Type: application/json
Content-Length: 94
{
"name": "Foo"
}
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Vary: Accept
Content-Type: application/json
{
"id": 2,
"name": "Foo",
"identifier": "south_entry"
}
:param organizer: The ``slug`` field of the organizer to modify
:param id: The ``id`` field of the gate to modify
:statuscode 200: no error
:statuscode 400: The gate could not be modified due to invalid submitted data
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer/gate does not exist **or** you have no permission to change this resource.
.. http:delete:: /api/v1/organizers/(organizer)/gates/(id)/
Delete a gate.
**Example request**:
.. sourcecode:: http
DELETE /api/v1/organizers/bigevents/gates/1/ HTTP/1.1
Host: pretix.eu
Accept: application/json, text/javascript
**Example response**:
.. sourcecode:: http
HTTP/1.1 204 No Content
Vary: Accept
:param organizer: The ``slug`` field of the organizer to modify
:param id: The ``id`` field of the gate to delete
:statuscode 204: no error
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer/gate does not exist **or** you have no permission to change it **or** this gate cannot be deleted since it is currently in use.
+1
View File
@@ -45,6 +45,7 @@ at :ref:`plugin-docs`.
carts
teams
devices
gates
webhooks
seatingplans
exporters
+4
View File
@@ -1065,6 +1065,7 @@ Creating orders
charge will be created), this is just informative in case you *handled the payment already*.
* ``payment_date`` (optional) – Date and time of the completion of the payment.
* ``tax_rounding_mode`` (optional)
* ``total`` (optional, will be computed from backend and operation will fail if the computation has a different result)
* ``comment`` (optional)
* ``custom_followup_at`` (optional)
* ``checkin_attention`` (optional)
@@ -1095,6 +1096,9 @@ Creating orders
* ``item``
* ``variation`` (optional)
* ``price`` (optional, if set to ``null`` or missing the price will be computed from the given product)
* ``tax_rule`` (optional, if set to ``null`` or missing the tax rule will be selected from the given product)
* ``tax_rate`` (optional, only works together with a tax rule, if set to ``null`` or missing the tax rate will be computed from the given tax rule)
* ``tax_code`` (optional, only works together with a tax rule, if set to ``null`` or missing the tax code will be computed from the given tax rule)
* ``seat`` (The ``seat_guid`` attribute of a seat. Required when the specified ``item`` requires a seat, otherwise must be ``null``.)
* ``attendee_name`` **or** ``attendee_name_parts`` (optional)
* ``voucher`` (optional, the ``code`` attribute of a valid voucher)
+27 -1
View File
@@ -284,7 +284,10 @@ In this algorithm, the tax value and gross total are computed from the sum of th
of some of the tickets will be changed automatically by the minimum currency unit (e.g. €0.01) such that the resulting
gross prices stay the same.
**This is less confusing to consumers and the end result is still compliant to EN 16931, so we recommend this for e-invoicing when (primarily) consumers are involved.**
**This is a bit less confusing to consumers and the end result is still compliant to EN 16931, so we recommend this for e-invoicing when (primarily) consumers are involved.**
However, confusion for consumers can still arise when a price cannot be represented by a net price.
For example, you cannot sell a single ticket for 15.00 with a 19 % tax rate, because 12.60 * 1.19 = 14.99 and 12.61 * 1.19 = 15.01, so a total gross price of 15.00 is impossible to reach and the system will round to a different gross price.
The main downside is that it might be confusing when selling to business customers, since the prices of the identical tickets appear to be different.
Full computation for the example above:
@@ -299,3 +302,26 @@ Full computation for the example above:
Ticket E 19 % 84.03 15.97 100.00
Sum 420.17 79.83 500.00
========== ========== ============================= ============================== =============
Compute taxes based on gross total
""""""""""""""""""""""""""""""""""
Algorithm identifier: ``sum_by_gross``
In this algorithm, the net prices of some the individual lines will be modified such that the end values will be consistent with a computation from the gross sum.
This will lead to different net prices to be shown for tickets of the same type, but the gross price will stay always the same.
**This is the most sensible algorithm when dealing mostly with consumer or when advertising gross prices, and you still need to issue e-invoices. Technically, it is not compliant with EN 16931, but at least for Germany, the Federal Ministry of Finance (BMF) allows to use it until end of 2027 in lieu of a better solution.**
For the example above:
========== ========== ============================= ============================== =============
Product Tax rate Net price Tax Gross price
========== ========== ============================= ============================== =============
Ticket A 19 % 84.04 (incl. 0.01 rounding) 15.96 (incl. -0.01 rounding) 100.00
Ticket B 19 % 84.04 (incl. 0.01 rounding) 15.96 (incl. -0.01 rounding) 100.00
Ticket C 19 % 84.03 15.97 100.00
Ticket D 19 % 84.03 15.97 100.00
Ticket E 19 % 84.03 15.97 100.00
Sum 420.17 79.83 500.00
========== ========== ============================= ============================== =============
-2
View File
@@ -43,8 +43,6 @@ const ignores = globalIgnores([
'src/pretix/static/pretixbase/js/addressform.js',
'src/pretix/static/pretixbase/js/asynctask.js',
'src/pretix/static/pretixbase/js/details.js',
'src/pretix/static/pretixbase/js/gettextstub.js',
'src/pretix/static/pretixbase/js/i18nstring.js',
'src/pretix/static/pretixcontrol/js/menu.js',
'src/pretix/static/pretixcontrol/js/ui/editor.js',
'src/pretix/static/pretixcontrol/js/ui/geo.js',
+1
View File
@@ -991,6 +991,7 @@ class DeviceEventSettingsSerializer(EventSettingsSerializer):
'system_question_order',
'tax_rule_payment',
'tax_rule_cancellation',
'tax_rounding',
]
def __init__(self, *args, **kwargs):
+153 -15
View File
@@ -608,7 +608,6 @@ class OrderPositionSerializer(I18nAwareModelSerializer):
fields = ('id', 'order', 'positionid', 'item', 'variation', 'price', 'attendee_name', 'attendee_name_parts',
'company', 'street', 'zipcode', 'city', 'country', 'state', 'discount',
'attendee_email', 'voucher', 'tax_rate', 'tax_value', 'secret', 'addon_to', 'subevent', 'checkins',
'print_logs', 'downloads', 'answers', 'tax_rule', 'pseudonymization_id', 'pdf_data', 'seat', 'canceled',
'print_logs', 'downloads', 'answers', 'tax_rule', 'tax_code', 'pseudonymization_id', 'pdf_data', 'seat',
'canceled', 'valid_from', 'valid_until', 'blocked', 'voucher_budget_use', 'plugin_data')
read_only_fields = (
@@ -1028,18 +1027,56 @@ class OrderFeeCreateSerializer(I18nAwareModelSerializer):
_treat_value_as_percentage = serializers.BooleanField(default=False, required=False)
_split_taxes_like_products = serializers.BooleanField(default=False, required=False)
tax_rate = serializers.DecimalField(required=False, decimal_places=4, max_digits=7)
tax_value = serializers.DecimalField(required=False, decimal_places=2, max_digits=13)
value_includes_rounding_correction = serializers.DecimalField(required=False, decimal_places=2, max_digits=13)
tax_value_includes_rounding_correction = serializers.DecimalField(required=False, decimal_places=2, max_digits=13)
class Meta:
model = OrderFee
fields = ('fee_type', 'value', 'description', 'internal_type', 'tax_rule',
'_treat_value_as_percentage', '_split_taxes_like_products')
fields = (
'fee_type', 'value', 'description', 'internal_type', 'tax_rule',
'_treat_value_as_percentage', '_split_taxes_like_products',
# The following fields should usually not be set by the client but computed by the backend. However, it makes
# sense to set them when the decision on the tax rate is made irrevertably on the client side, such as with
# pretixPOS.
'tax_rate', 'tax_code',
# The following fields are undocumented and only used by pretixPOS. They do *NOT* override the calculations
# by the backends but are checked against them and must match exactly, otherwise the entire operation is
# aborted to avoid diverging tax values between POS reports and backend reports.
'tax_value', 'value_includes_rounding_correction', 'tax_value_includes_rounding_correction',
)
def validate_tax_rule(self, tr):
if tr and tr.event != self.context['event']:
raise ValidationError(
'The specified tax rate does not belong to this event.'
'The specified tax rule does not belong to this event.'
)
return tr
def validate(self, attrs):
if attrs.get('_treat_value_as_percentage'):
for k in ('tax_value', 'value_includes_rounding_correction', 'tax_value_includes_rounding_correction'):
if k in attrs:
raise ValidationError({
k: ['You cannot ask for the value to be treated as a percentage if you already computed taxes.']
})
if attrs.get('_split_taxes_like_products'):
for k in ('tax_rate', 'tax_value', 'value_includes_rounding_correction', 'tax_value_includes_rounding_correction'):
if k in attrs:
raise ValidationError({
k: ['You cannot ask for the value to be distributed over tax rates if you already set the tax rate or computed taxes.']
})
if 'tax_rate' in attrs and 'tax_rule' not in attrs:
raise ValidationError({
'tax_rate': ['Tax rate cannot be stored without tax rule.']
})
if 'value_includes_rounding_correction' in attrs:
# Make all computations like discounts on the price before rounding, later compare against rounding again
attrs['value'] = attrs['value'] - attrs['value_includes_rounding_correction']
return attrs
class OrderPositionCreateSerializer(I18nAwareModelSerializer):
answers = AnswerCreateSerializer(many=True, required=False)
@@ -1055,13 +1092,27 @@ class OrderPositionCreateSerializer(I18nAwareModelSerializer):
requested_valid_from = serializers.DateTimeField(required=False, allow_null=True)
use_reusable_medium = serializers.PrimaryKeyRelatedField(queryset=ReusableMedium.objects.none(),
required=False, allow_null=True)
tax_rate = serializers.DecimalField(required=False, decimal_places=4, max_digits=7)
tax_value = serializers.DecimalField(required=False, decimal_places=2, max_digits=13)
price_includes_rounding_correction = serializers.DecimalField(required=False, decimal_places=2, max_digits=13)
tax_value_includes_rounding_correction = serializers.DecimalField(required=False, decimal_places=2, max_digits=13)
class Meta:
model = OrderPosition
fields = ('positionid', 'item', 'variation', 'price', 'attendee_name', 'attendee_name_parts', 'attendee_email',
'company', 'street', 'zipcode', 'city', 'country', 'state', 'is_bundled',
'secret', 'addon_to', 'subevent', 'answers', 'seat', 'voucher', 'valid_from', 'valid_until',
'requested_valid_from', 'use_reusable_medium', 'discount')
fields = (
'positionid', 'item', 'variation', 'price', 'attendee_name', 'attendee_name_parts', 'attendee_email',
'company', 'street', 'zipcode', 'city', 'country', 'state', 'is_bundled',
'secret', 'addon_to', 'subevent', 'answers', 'seat', 'voucher', 'valid_from', 'valid_until',
'requested_valid_from', 'use_reusable_medium', 'discount',
# The following fields should usually not be set by the client but computed by the backend. However, it makes
# sense to set them when the decision on the tax rate is made irrevertably on the client side, such as with
# pretixPOS.
'tax_rule', 'tax_rate', 'tax_code',
# The following fields are undocumented and only used by pretixPOS. They do *NOT* override the calculations
# by the backends but are checked against them and must match exactly, otherwise the entire operation is
# aborted to avoid diverging tax values between POS reports and backend reports.
'tax_value', 'price_includes_rounding_correction', 'tax_value_includes_rounding_correction',
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@@ -1099,6 +1150,13 @@ class OrderPositionCreateSerializer(I18nAwareModelSerializer):
)
return item
def validate_tax_rule(self, tax_rule):
if tax_rule.event != self.context['event']:
raise ValidationError(
'The specified tax rule does not belong to this event.'
)
return tax_rule
def validate_subevent(self, subevent):
if self.context['event'].has_subevents:
if not subevent:
@@ -1162,6 +1220,15 @@ class OrderPositionCreateSerializer(I18nAwareModelSerializer):
{'discount': ['You can only specify a discount if you do the price computation, but price is not set.']}
)
if 'tax_rate' in data and 'tax_rule' not in data and not data['item'].tax_rule_id:
raise ValidationError({
'tax_rate': ['Tax rate cannot be stored without tax rule.']
})
if 'price_includes_rounding_correction' in data:
# Make all computations like discounts on the price before rounding, later compare against rounding again
data['price'] = data['price'] - data['price_includes_rounding_correction']
return data
@@ -1219,6 +1286,7 @@ class OrderCreateSerializer(I18nAwareModelSerializer):
tax_rounding_mode = serializers.ChoiceField(choices=ROUNDING_MODES, allow_null=True, required=False,)
locale = serializers.ChoiceField(choices=[], required=False, allow_null=True)
use_gift_cards = serializers.ListField(child=serializers.CharField(required=False), required=False)
total = serializers.DecimalField(required=False, decimal_places=2, max_digits=13)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@@ -1233,7 +1301,7 @@ class OrderCreateSerializer(I18nAwareModelSerializer):
model = Order
fields = ('code', 'status', 'testmode', 'email', 'phone', 'locale', 'payment_provider', 'fees', 'comment', 'sales_channel',
'invoice_address', 'positions', 'checkin_attention', 'checkin_text', 'payment_info', 'payment_date',
'consume_carts', 'force', 'send_email', 'simulate', 'customer', 'custom_followup_at',
'consume_carts', 'force', 'send_email', 'simulate', 'customer', 'custom_followup_at', 'total',
'require_approval', 'valid_if_pending', 'expires', 'api_meta', 'tax_rounding_mode', 'use_gift_cards')
def validate_payment_provider(self, pp):
@@ -1573,6 +1641,7 @@ class OrderCreateSerializer(I18nAwareModelSerializer):
if validated_data.get('locale', None) is None:
validated_data['locale'] = self.context['event'].settings.locale
expected_total = validated_data.pop('total', None)
order = Order(event=self.context['event'], **validated_data)
if not validated_data.get('expires'):
order.set_expires(subevents=[p.get('subevent') for p in positions_data])
@@ -1604,7 +1673,14 @@ class OrderCreateSerializer(I18nAwareModelSerializer):
pos_data['attendee_name_parts'] = {
'_legacy': attendee_name
}
pos = OrderPosition(**{k: v for k, v in pos_data.items() if k not in ('answers', '_quotas', 'use_reusable_medium')})
pos = OrderPosition(**{k: v for k, v in pos_data.items() if k not in (
'answers',
'_quotas',
'use_reusable_medium',
'tax_value',
'price_includes_rounding_correction',
'tax_value_includes_rounding_correction',
)})
if simulate:
pos.order = order._wrapped
else:
@@ -1647,7 +1723,12 @@ class OrderCreateSerializer(I18nAwareModelSerializer):
if not pos.item.tax_rule or pos.item.tax_rule.price_includes_tax:
price_after_voucher = max(pos.price, pos.voucher.calculate_price(listed_price))
else:
pos._calculate_tax(invoice_address=ia)
pos._calculate_tax(
invoice_address=ia,
tax_rule=pos_data.get('tax_rule'),
override_tax_rate=pos_data.get('tax_rate'),
override_tax_code=pos_data.get('tax_code'),
)
price_after_voucher = max(pos.price - pos.tax_value, pos.voucher.calculate_price(listed_price))
else:
price_after_voucher = listed_price
@@ -1679,7 +1760,12 @@ class OrderCreateSerializer(I18nAwareModelSerializer):
answers_data = pos_data.pop('answers', [])
use_reusable_medium = pos_data.pop('use_reusable_medium', None)
pos = pos_data['__instance']
pos._calculate_tax(invoice_address=ia)
pos._calculate_tax(
invoice_address=ia,
tax_rule=pos_data.get('tax_rule', None),
override_tax_rate=pos_data.get('tax_rate'),
override_tax_code=pos_data.get('tax_code'),
)
if simulate:
pos = WrappedModel(pos)
@@ -1778,7 +1864,11 @@ class OrderCreateSerializer(I18nAwareModelSerializer):
for tr, val in fee_values:
fee_data['tax_rule'] = tr
fee_data['value'] = val
f = OrderFee(**fee_data)
f = OrderFee(**{k: v for k, v in fee_data.items() if k not in (
'tax_value',
'value_includes_rounding_correction',
'tax_value_includes_rounding_correction'
)})
f.order = order._wrapped if simulate else order
f._calculate_tax()
fees.append(f)
@@ -1787,9 +1877,17 @@ class OrderCreateSerializer(I18nAwareModelSerializer):
else:
f.save()
else:
f = OrderFee(**fee_data)
f = OrderFee(**{k: v for k, v in fee_data.items() if k not in (
'tax_value',
'value_includes_rounding_correction',
'tax_value_includes_rounding_correction'
)})
f.order = order._wrapped if simulate else order
f._calculate_tax()
f._calculate_tax(
override_tax_rate=fee_data.get('tax_rate'),
override_tax_code=fee_data.get('tax_code'),
)
fee_data['__instance'] = f
fees.append(f)
if simulate:
f.id = 0
@@ -1821,7 +1919,47 @@ class OrderCreateSerializer(I18nAwareModelSerializer):
"value", "value_includes_rounding_correction", "tax_value", "tax_value_includes_rounding_correction"
])
for i, pos_data in enumerate(positions_data):
pos = pos_data['__instance']
if 'tax_value' in pos_data and pos_data['tax_value'] != pos.tax_value:
raise ValidationError(f'Tax value {pos_data["tax_value"]} in position {pos.positionid} does not match backend computation of {pos.tax_value}.')
if 'price_includes_rounding_correction' in pos_data and pos_data['price_includes_rounding_correction'] != pos.price_includes_rounding_correction:
raise ValidationError(
f'Price rounding {pos_data["price_includes_rounding_correction"]} in position {pos.positionid} does not '
f'match backend computation of {pos.price_includes_rounding_correction}.'
)
if ('tax_value_includes_rounding_correction' in pos_data and
pos_data['tax_value_includes_rounding_correction'] != pos.tax_value_includes_rounding_correction):
raise ValidationError(
f'Tax rounding {pos_data["tax_value_includes_rounding_correction"]} in position {pos.positionid} does not '
f'match backend computation of {pos.tax_value_includes_rounding_correction}.'
)
for i, fee_data in enumerate(fees_data):
if '__instance' not in fee_data: # split fee not supported for this, validated in OrderFeeCreateSerializer
continue
fee = fee_data['__instance']
if 'tax_value' in fee_data and fee_data['tax_value'] != fee.tax_value:
raise ValidationError(f'Tax value {fee_data["tax_value"]} in fee does not match backend computation of {fee.tax_value}.')
if 'value_includes_rounding_correction' in fee_data and fee_data['value_includes_rounding_correction'] != fee.value_includes_rounding_correction:
raise ValidationError(
f'Price rounding {fee_data["value_includes_rounding_correction"]} in fee does not '
f'match backend computation of {fee.value_includes_rounding_correction}.'
)
if ('tax_value_includes_rounding_correction' in fee_data and
fee_data['tax_value_includes_rounding_correction'] != fee.tax_value_includes_rounding_correction):
raise ValidationError(
f'Tax rounding {fee_data["tax_value_includes_rounding_correction"]} in fee does not '
f'match backend computation of {fee.tax_value_includes_rounding_correction}.'
)
order.total = sum([c.price for c in pos_map.values()]) + sum([f.value for f in fees])
if expected_total is not None and expected_total != order.total:
raise ValidationError({
'total': [f'Order total of {expected_total} does not match backend computation of {order.total}.']
})
if simulate:
order.fees = fees
order.positions = pos_map.values()
+8 -1
View File
@@ -41,7 +41,7 @@ from pretix.api.serializers.settings import SettingsSerializer
from pretix.base.auth import get_auth_backends
from pretix.base.i18n import get_language_without_region
from pretix.base.models import (
Customer, Device, EventMetaProperty, GiftCard, GiftCardTransaction,
Customer, Device, EventMetaProperty, Gate, GiftCard, GiftCardTransaction,
Membership, MembershipType, OrderPosition, Organizer, ReusableMedium,
SalesChannel, SeatingPlan, Team, TeamAPIToken, TeamInvite, User,
)
@@ -477,6 +477,13 @@ class DeviceSerializer(serializers.ModelSerializer):
del self.fields['initialization_token']
class GateSerializer(serializers.ModelSerializer):
class Meta:
model = Gate
fields = ('id', 'name', 'identifier')
class TeamInviteSerializer(serializers.ModelSerializer):
class Meta:
model = TeamInvite
+1
View File
@@ -62,6 +62,7 @@ orga_router.register(r'membershiptypes', organizer.MembershipTypeViewSet)
orga_router.register(r'reusablemedia', media.ReusableMediaViewSet)
orga_router.register(r'teams', organizer.TeamViewSet)
orga_router.register(r'devices', organizer.DeviceViewSet)
orga_router.register(r'gates', organizer.GateViewSet)
orga_router.register(r'orders', order.OrganizerOrderViewSet)
orga_router.register(r'invoices', order.InvoiceViewSet)
orga_router.register(r'scheduled_exports', exporters.ScheduledOrganizerExportViewSet)
+50 -4
View File
@@ -44,16 +44,16 @@ from pretix.api.models import OAuthAccessToken
from pretix.api.pagination import TotalOrderingFilter
from pretix.api.serializers.organizer import (
CustomerCreateSerializer, CustomerSerializer, DeviceSerializer,
EventMetaPropertiesSerializer, GiftCardSerializer,
EventMetaPropertiesSerializer, GateSerializer, GiftCardSerializer,
GiftCardTransactionSerializer, MembershipSerializer,
MembershipTypeSerializer, OrganizerSerializer, OrganizerSettingsSerializer,
SalesChannelSerializer, SeatingPlanSerializer, TeamAPITokenSerializer,
TeamInviteSerializer, TeamMemberSerializer, TeamSerializer,
)
from pretix.base.models import (
Customer, Device, Event, EventMetaProperty, GiftCard, GiftCardTransaction,
LogEntry, Membership, MembershipType, Organizer, SalesChannel, SeatingPlan,
Team, TeamAPIToken, TeamInvite, User,
Customer, Device, Event, EventMetaProperty, Gate, GiftCard,
GiftCardTransaction, LogEntry, Membership, MembershipType, Organizer,
SalesChannel, SeatingPlan, Team, TeamAPIToken, TeamInvite, User,
)
from pretix.base.plugins import (
PLUGIN_LEVEL_EVENT, PLUGIN_LEVEL_EVENT_ORGANIZER_HYBRID,
@@ -571,6 +571,52 @@ class DeviceViewSet(mixins.CreateModelMixin,
return inst
class GateViewSet(viewsets.ModelViewSet):
serializer_class = GateSerializer
queryset = Gate.objects.none()
permission = 'organizer.devices:read'
write_permission = 'organizer.devices:write'
def get_queryset(self):
return self.request.organizer.gates.order_by('pk')
def get_serializer_context(self):
ctx = super().get_serializer_context()
ctx['organizer'] = self.request.organizer
return ctx
@transaction.atomic()
def perform_destroy(self, instance):
instance.log_action(
'pretix.gate.deleted',
user=self.request.user,
auth=self.request.auth,
data={'id': instance.pk}
)
instance.delete()
@transaction.atomic()
def perform_create(self, serializer):
inst = serializer.save(organizer=self.request.organizer)
inst.log_action(
'pretix.gate.created',
user=self.request.user,
auth=self.request.auth,
data=merge_dicts(self.request.data, {'id': inst.pk})
)
@transaction.atomic()
def perform_update(self, serializer):
inst = serializer.save()
inst.log_action(
'pretix.gate.changed',
user=self.request.user,
auth=self.request.auth,
data=self.request.data
)
return inst
class OrganizerSettingsView(views.APIView):
permission = None
write_permission = 'organizer.settings.general:write'
+1 -1
View File
@@ -287,7 +287,7 @@ class NamePartsFormField(forms.MultiValueField):
v = value.get(fname)
if not v:
continue
special_chars = re.findall('[$€/%§{}<>~]', v)
special_chars = re.findall('[$€/%§{}<>~=]', v)
if special_chars:
raise forms.ValidationError(
_('The field "%(label)s" may not contain special characters such as "%(chars)s".'),
-47
View File
@@ -24,7 +24,6 @@ import uuid
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.db.models.constants import LOOKUP_SEP
from django.db.models.signals import post_delete
from django.dispatch import receiver
from django.urls import reverse
@@ -245,49 +244,3 @@ class LoggedModel(models.Model, LoggingMixin):
return LogEntry.objects.filter(
content_type=self.logs_content_type, object_id=self.pk
).select_related('user', 'event', 'event__organizer', 'oauth_application', 'api_token', 'device')
class LockModel:
def refresh_for_update(self, fields=None, using=None, **kwargs):
"""
Like refresh_from_db(), but with select_for_update().
See also https://code.djangoproject.com/ticket/28344
"""
if fields is not None:
if not fields:
return
if any(LOOKUP_SEP in f for f in fields):
raise ValueError(
'Found "%s" in fields argument. Relations and transforms '
'are not allowed in fields.' % LOOKUP_SEP)
hints = {'instance': self}
db_instance_qs = self.__class__._base_manager.db_manager(using, hints=hints).filter(pk=self.pk).select_for_update(**kwargs)
# Use provided fields, if not set then reload all non-deferred fields.
deferred_fields = self.get_deferred_fields()
if fields is not None:
fields = list(fields)
db_instance_qs = db_instance_qs.only(*fields)
elif deferred_fields:
fields = [f.attname for f in self._meta.concrete_fields
if f.attname not in deferred_fields]
db_instance_qs = db_instance_qs.only(*fields)
db_instance = db_instance_qs.get()
non_loaded_fields = db_instance.get_deferred_fields()
for field in self._meta.concrete_fields:
if field.attname in non_loaded_fields:
# This field wasn't refreshed - skip ahead.
continue
setattr(self, field.attname, getattr(db_instance, field.attname))
# Clear cached foreign keys.
if field.is_relation and field.is_cached(self):
field.delete_cached_value(self)
# Clear cached relations.
for field in self._meta.related_objects:
if field.is_cached(self):
field.delete_cached_value(self)
self._state.db = db_instance._state.db
+2 -1
View File
@@ -621,7 +621,8 @@ class Item(LoggedModel):
verbose_name=_('This product can only be bought using a voucher.'),
default=False,
help_text=_('To buy this product, the user needs a voucher that applies to this product '
'either directly or via a quota.')
'either directly or via a quota. Please note that the waitinglist is not '
'available for products requiring a voucher.')
)
require_approval = models.BooleanField(
verbose_name=_('Buying this product requires approval'),
+11 -8
View File
@@ -93,7 +93,7 @@ from ...testutils.middleware import debugflags_var
from ._transactions import (
_fail, _transactions_mark_order_clean, _transactions_mark_order_dirty,
)
from .base import LockModel, LoggedModel
from .base import LoggedModel
from .event import Event, SubEvent
from .items import Item, ItemVariation, Question, QuestionOption, Quota
@@ -136,7 +136,7 @@ class OrderQuerySet(models.QuerySet):
return order
class Order(LockModel, LoggedModel):
class Order(LoggedModel):
"""
An order is created when a user clicks 'buy' on his cart. It holds
several OrderPositions and is connected to a user. It has an
@@ -2431,7 +2431,7 @@ class OrderFee(RoundingCorrectionMixin, models.Model):
self.fee_type, self.value
)
def _calculate_tax(self, tax_rule=None, invoice_address=None, event=None):
def _calculate_tax(self, tax_rule=None, invoice_address=None, event=None, override_tax_rate=None, override_tax_code=None):
if tax_rule:
self.tax_rule = tax_rule
@@ -2450,7 +2450,8 @@ class OrderFee(RoundingCorrectionMixin, models.Model):
self.tax_rule = event.cached_default_tax_rule
if self.tax_rule:
tax = self.tax_rule.tax(self.value, base_price_is='gross', invoice_address=ia, force_fixed_gross_price=True)
tax = self.tax_rule.tax(self.value, base_price_is='gross', invoice_address=ia, force_fixed_gross_price=True,
override_tax_rate=override_tax_rate, override_tax_code=override_tax_code)
self.tax_rate = tax.rate
self.tax_code = tax.code
self.tax_value = tax.tax
@@ -2813,14 +2814,15 @@ class OrderPosition(AbstractPosition):
self.item.id, self.variation.id if self.variation else 0, self.order_id
)
def _calculate_tax(self, tax_rule=None, invoice_address=None):
def _calculate_tax(self, tax_rule=None, invoice_address=None, override_tax_rate=None, override_tax_code=None):
self.tax_rule = tax_rule or self.item.tax_rule
try:
ia = invoice_address or self.order.invoice_address
except InvoiceAddress.DoesNotExist:
ia = None
if self.tax_rule:
tax = self.tax_rule.tax(self.price, invoice_address=ia, base_price_is='gross', force_fixed_gross_price=True)
tax = self.tax_rule.tax(self.price, invoice_address=ia, base_price_is='gross', force_fixed_gross_price=True,
override_tax_rate=override_tax_rate, override_tax_code=override_tax_code)
self.tax_rate = tax.rate
self.tax_code = tax.code
self.tax_value = tax.tax
@@ -3358,11 +3360,12 @@ class CartPosition(AbstractPosition):
bundled_sum=sum([b.price_after_voucher for b in bundled_positions]),
is_bundled=self.is_bundled,
)
if line_price.gross != self.line_price_gross or line_price.rate != self.tax_rate:
if line_price.gross != self.line_price_gross or line_price.rate != self.tax_rate or line_price.code != self.tax_code:
self.line_price_gross = line_price.gross
self.tax_rate = line_price.rate
self.tax_code = line_price.code
self.save(update_fields=['line_price_gross', 'tax_rate'])
self.save(update_fields=['line_price_gross', 'tax_rate', 'tax_code'])
@property
def discount_percentage(self):
+1 -2
View File
@@ -28,7 +28,6 @@ from django.db import DatabaseError, connection
from django.utils.timezone import now
from pretix.base.models import Event, Membership, Quota, Seat, Voucher
from pretix.helpers import OF_SELF
from pretix.testutils.middleware import debugflags_var
logger = logging.getLogger('pretix.base.locking')
@@ -120,7 +119,7 @@ def lock_objects(objects, *, shared_lock_objects=None, replace_exclusive_with_sh
else:
for model, instances in groupby(objects, key=lambda o: type(o)):
model.objects.select_for_update(of=OF_SELF).filter(pk__in=[o.pk for o in instances])
model.objects.select_for_update().filter(pk__in=[o.pk for o in instances])
class NoLockManager:
+40 -2
View File
@@ -211,7 +211,8 @@ def apply_discounts(event: Event, sales_channel: Union[str, SalesChannel],
return [new_prices.get(idx, (p[3], None)) for idx, p in enumerate(positions)]
def apply_rounding(rounding_mode: Literal["line", "sum_by_net", "sum_by_net_only_business", "sum_by_net_keep_gross"],
def apply_rounding(rounding_mode: Literal["line", "sum_by_net", "sum_by_net_only_business", "sum_by_net_keep_gross",
"sum_by_gross", "sum_by_net_business_else_gross"],
invoice_address: Optional[InvoiceAddress], currency: str,
lines: List[Union[OrderPosition, CartPosition, OrderFee]]) -> list:
"""
@@ -227,7 +228,11 @@ def apply_rounding(rounding_mode: Literal["line", "sum_by_net", "sum_by_net_only
When rounding mode is set to ``"sum_by_net"``, the gross prices and tax values of the individual lines will be
adjusted such that the per-taxrate/taxcode subtotal is rounded correctly. The net prices will stay constant.
:param rounding_mode: One of ``"line"``, ``"sum_by_net"``, ``"sum_by_net_only_business"``, or ``"sum_by_net_keep_gross"``.
When rounding mode is set to ``"sum_by_gross"``, the net prices and tax values of the individual lines will be
adjusted such that the per-taxrate/taxcode subtotal is rounded correctly. The gross prices will stay constant.
:param rounding_mode: One of ``"line"``, ``"sum_by_net"``, ``"sum_by_net_only_business"``, ``"sum_by_net_keep_gross"``,
``"sum_by_gross"``, or ``"sum_by_net_business_else_gross"``.
:param invoice_address: The invoice address, or ``None``
:param currency: Currency that will be used to determine rounding precision
:param lines: List of order/cart contents
@@ -238,6 +243,11 @@ def apply_rounding(rounding_mode: Literal["line", "sum_by_net", "sum_by_net_only
rounding_mode = "sum_by_net"
else:
rounding_mode = "line"
elif rounding_mode == "sum_by_net_business_else_gross":
if invoice_address and invoice_address.is_business:
rounding_mode = "sum_by_net"
else:
rounding_mode = "sum_by_gross"
def _key(line):
return (line.tax_rate, line.tax_code or "")
@@ -321,6 +331,34 @@ def apply_rounding(rounding_mode: Literal["line", "sum_by_net", "sum_by_net_only
l.tax_value_includes_rounding_correction = Decimal("0.00")
changed.append(l)
elif rounding_mode == "sum_by_gross":
for (tax_rate, tax_code), lines in groupby(sorted(lines, key=_key), key=_key):
lines = list(sorted(lines, key=lambda l: -(l.gross_price_before_rounding)))
net_total = sum(
l.gross_price_before_rounding - l.tax_value_before_rounding
for l in lines
)
gross_total = sum(l.gross_price_before_rounding for l in lines)
target_net_total = round_decimal(gross_total - (gross_total * (1 - 100 / (100 + tax_rate))), currency)
diff = target_net_total - net_total
diff_sgn = -1 if diff < 0 else 1
for l in lines:
if diff:
apply_diff = diff_sgn * minimum_unit
l.price = l.gross_price_before_rounding
l.price_includes_rounding_correction = Decimal("0.00")
l.tax_value = l.tax_value_before_rounding - apply_diff
l.tax_value_includes_rounding_correction = -apply_diff
diff -= apply_diff
changed.append(l)
elif l.price_includes_rounding_correction or l.tax_value_includes_rounding_correction:
l.price = l.gross_price_before_rounding
l.price_includes_rounding_correction = Decimal("0.00")
l.tax_value = l.tax_value_before_rounding
l.tax_value_includes_rounding_correction = Decimal("0.00")
changed.append(l)
elif rounding_mode == "line":
for l in lines:
if l.price_includes_rounding_correction or l.tax_value_includes_rounding_correction:
+4 -2
View File
@@ -81,9 +81,11 @@ from pretix.helpers.countries import CachedCountries, pycountry_add
ROUNDING_MODES = (
('line', _('Compute taxes for every line individually')),
('sum_by_net', _('Compute taxes based on net total')),
('sum_by_net_only_business', _('For business customers, compute taxes based on net total. For individuals, use line-based rounding')),
('sum_by_gross', _('Compute taxes based on gross total')),
('sum_by_net_business_else_gross', _('For business customers, compute taxes based on net total. For individuals, compute taxes based on gross total.')),
('sum_by_net_keep_gross', _('Compute taxes based on net total with stable gross prices')),
# We could also have sum_by_gross, but we're not aware of any use-cases for it
('sum_by_net_only_business',
_('For business customers, compute taxes based on net total. For individuals, use line-based rounding')),
)
+1 -5
View File
@@ -23,17 +23,13 @@ from django import template
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from pretix.helpers.templatetags.simple_block_tag import (
register_simple_block_tag,
)
from django.utils.translation import gettext_lazy as _ # NOQA
register = template.Library()
@register_simple_block_tag(register)
@register.simple_block_tag
def dialog(content, html_id, title, description, *args, **kwargs):
format_kwargs = {
"id": html_id,
+28 -13
View File
@@ -974,26 +974,41 @@ class TaxSettingsForm(EventSettingsValidationMixin, SettingsForm):
self.fields["display_net_prices"].widget = DisplayNetPricesBooleanSelect()
help_text = {
"line": _(
"Recommended when e-invoicing is not required. Each product will be sold with the advertised "
"net and gross price. However, in orders of more than one product, the total tax amount "
"can differ from when it would be computed from the order total."
"Each product will be sold with the advertised net and gross price. Net and gross prices stay stable on "
"order splits. However, in orders of more than one product, the total tax amount can differ from when "
"it would be computed from the order total."
),
"sum_by_net": _(
"Recommended for e-invoicing when you primarily sell to business customers and "
"show prices to customers excluding tax. "
"show prices to customers excluding tax. Created e-invoices are fully compliant with EN 16931. "
"The gross price of some products may be changed to ensure correct rounding, while the net "
"prices will be kept as configured. This may cause the actual payment amount to differ."
),
"sum_by_net_only_business": _(
"Same as above, but only applied to business customers. Line-based rounding will be used for consumers. "
"Recommended when e-invoicing is only used for business customers and consumers do not receive "
"invoices. This can cause the payment amount to change when the invoice address is changed."
"sum_by_gross": _(
"Recommended for e-invoicing when you primarily sell to consumers or show prices to customers including tax. "
"The net price of some products may be changed to ensure correct rounding, while the gross "
"prices will be kept as configured. This actual payment amount always stays as expected. This is "
"technically not compliant with European e-invoicing standards, but e.g. allowed within Germany at "
"least until end of 2027."
),
"sum_by_net_keep_gross": _(
"Recommended for e-invoicing when you primarily sell to consumers. "
"The gross or net price of some products may be changed automatically to ensure correct "
"rounding of the order total. The system attempts to keep gross prices as configured whenever "
"possible. Gross prices may still change if they are impossible to derive from a rounded net price."
"sum_by_net_business_else_gross": _(
"Recommended if you sell to business customers who care about e-invoices compliant to EN 16931 and to "
"consumers who care about advertised prices at the same time. However, this can cause the payment amount "
"to change when the invoice address is changed."
),
"sum_by_net_keep_gross": format_html(
"<span class='label label-default'>{}</span> {}",
_('Not recommended'),
_(
"The gross or net price of some products may be changed automatically to ensure correct "
"rounding of the order total. The system attempts to keep gross prices as configured whenever "
"possible. Gross prices may still change if they are impossible to derive from a rounded net price."
)
),
"sum_by_net_only_business": format_html(
"<span class='label label-default'>{}</span> {}",
_('Not recommended'),
"This can cause the payment amount to change when the invoice address is changed."
),
}
self.fields["tax_rounding"].choices = (
@@ -39,6 +39,16 @@
</button>
{% endif %}
</dd>
<dt>{% trans "Claim token" context "reusable_media" %}</dt>
<dd>
{% if medium.claim_token %}
{% if staff_session %}
<code>{{ medium.claim_token }}</code>
{% else %}
*****
{% endif %}
{% endif %}
</dd>
<dt>{% trans "Status" %}</dt>
<dd>
{% if not medium.active %}
@@ -242,20 +242,26 @@
<p>&nbsp;</p>
<fieldset>
<legend>{% trans "Check-in lists" %}</legend>
{% if sampled_lists|default_if_none:"NONE" == "NONE" %}
{% if block_list_change %}
<div class="alert alert-info">
{% blocktrans trimmed %}
You selected a set of dates that currently have different check-in list setups. You can
therefore not change their check-in lists in bulk.
You selected a set of dates that currently have different check-in list setups and already
contain checkins. You can therefore not change their check-in lists in bulk.
{% endblocktrans %}
</div>
{% else %}
<div class="bulk-edit-field-group">
<label class="field-toggle">
<input type="checkbox" name="_bulk" value="__checkinlists" {% if "__checkinlists" in bulk_selected %}checked{% endif %}>
{% trans "change" context "form_bulk" %}
</label>
<div class="field-content">
<div class="bulk-edit-field-group">
<label class="field-toggle">
<input type="checkbox" name="_bulk" value="__checkinlists" {% if "__checkinlists" in bulk_selected %}checked{% endif %}>
{% trans "change" context "form_bulk" %}
</label>
<div class="field-content">
{% if sampled_lists|default_if_none:"NONE" == "NONE" %}
<div class="alert alert-warning">
{% trans "You selected a set of dates that currently have different check-in list setups." %}
{% trans "Using this option will <strong>delete all current check-in lists</strong> from <strong>all selected dates</strong>." %}
</div>
{% endif %}
<div class="formset" data-formset data-formset-prefix="{{ cl_formset.prefix }}">
{{ cl_formset.management_form }}
{% bootstrap_formset_errors cl_formset %}
+32 -4
View File
@@ -60,7 +60,7 @@ from django.views.generic import (
)
from pretix.base.models import CartPosition, LogEntry, OrderPosition
from pretix.base.models.checkin import CheckinList
from pretix.base.models.checkin import Checkin, CheckinList
from pretix.base.models.event import SubEvent, SubEventMetaValue
from pretix.base.models.items import (
Item, ItemVariation, Quota, SubEventItem, SubEventItemVariation,
@@ -1320,9 +1320,13 @@ class SubEventBulkEdit(SubEventQueryMixin, EventPermissionRequiredMixin, FormVie
extra = 0
kwargs = {}
if self.sampled_lists is None:
if self.block_list_change:
return None
kwargs['instance'] = self.get_queryset()[0]
if self.sampled_lists is not None:
try:
kwargs['instance'] = self.get_queryset()[0]
except IndexError:
raise Http404("No matching dates")
formsetclass = inlineformset_factory(
SubEvent, CheckinList,
@@ -1335,7 +1339,7 @@ class SubEventBulkEdit(SubEventQueryMixin, EventPermissionRequiredMixin, FormVie
)
def save_list_formset(self, log_entries):
if self.sampled_lists is None or not self.list_formset.has_changed():
if self.block_list_change or not self.list_formset.has_changed():
return
qidx = 0
subevents = list(self.get_queryset().prefetch_related('checkinlist_set'))
@@ -1343,6 +1347,21 @@ class SubEventBulkEdit(SubEventQueryMixin, EventPermissionRequiredMixin, FormVie
to_save_gates = []
to_delete_list_ids = []
if self.sampled_lists is None:
if len(self.list_formset.forms) == 0:
return
else:
for se in subevents:
for q in se.checkinlist_set.all():
to_delete_list_ids.append(q.pk)
log_entries += [
q.log_action(action='pretix.event.checkinlist.deleted', user=self.request.user, save=False),
]
if to_delete_list_ids:
CheckinList.objects.filter(id__in=to_delete_list_ids).delete()
to_delete_list_ids = []
for f in self.list_formset.forms:
if self.list_formset._should_delete_form(f) and f in self.list_formset.extra_forms:
continue
@@ -1494,6 +1513,7 @@ class SubEventBulkEdit(SubEventQueryMixin, EventPermissionRequiredMixin, FormVie
ctx['filter_form'] = self.filter_form
ctx['sampled_quotas'] = self.sampled_quotas
ctx['sampled_lists'] = self.sampled_lists
ctx['block_list_change'] = self.block_list_change
ctx['formset'] = self.quota_formset
ctx['cl_formset'] = self.list_formset
ctx['itemvar_forms'] = self.itemvar_forms
@@ -1540,6 +1560,14 @@ class SubEventBulkEdit(SubEventQueryMixin, EventPermissionRequiredMixin, FormVie
return None
return se.quotas.all()
@cached_property
def block_list_change(self):
if self.sampled_lists:
return False # all the same, safe to change
return Checkin.all.filter(
list__subevent__in=self.get_queryset()
).exists()
@cached_property
def sampled_lists(self):
all_lists = CheckinList.objects.filter(
+1 -1
View File
@@ -32,9 +32,9 @@
# 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 csv
import io
from defusedcsv import csv
from django.contrib import messages
from django.db import transaction
from django.db.models import F, Max, Min, Q, Sum
-2
View File
@@ -30,8 +30,6 @@ class PretixHelpersConfig(AppConfig):
from .monkeypatching import monkeypatch_all_at_ready
monkeypatch_all_at_ready()
from .database import guard_select_for_update # noqa
# Ensure reportlab does not make any calls to the internet or the local disk
from reportlab import rl_config
rl_config.trustedHosts = []
-28
View File
@@ -20,32 +20,22 @@
# <https://www.gnu.org/licenses/>.
#
import contextlib
import logging
import re
from django.conf import settings
from django.contrib.postgres.indexes import BrinIndex
from django.core.exceptions import FieldDoesNotExist, ImproperlyConfigured
from django.db import connection, transaction
from django.db.backends.signals import connection_created
from django.db.models import (
Aggregate, Expression, F, Field, Func, IntegerField, JSONField, Lookup,
OrderBy, Value,
)
from django.dispatch import receiver
from django.utils.functional import lazy
logger = logging.getLogger(__name__)
class DummyRollbackException(Exception):
pass
class UnsafeSQLQueryException(Exception):
pass
@contextlib.contextmanager
def rolledback_transaction():
"""
@@ -334,21 +324,3 @@ class UnixTimestamp(Func):
def as_sqlite(self, compiler, connection):
return self.as_sql(compiler, connection, template="CAST(strftime('%%%%s', datetime(%(expressions)s)) AS INT)")
REGEX = re.compile(r'FOR (NO KEY )?UPDATE(?! OF)')
def query_wrapper_select_for_update(execute, sql, params, many, context):
if REGEX.search(sql) and "JOIN" in sql:
if settings.DEBUG:
raise UnsafeSQLQueryException("Never use 'FOR UPDATE' without 'OF' if query causes any JOINs")
else:
logger.warning("SQL used 'FOR UPDATE' without 'OF' if query causes any JOINs", stack_info=True)
return execute(sql, params, many, context)
@receiver(connection_created)
def guard_select_for_update(sender, connection, **kwargs):
if query_wrapper_select_for_update not in connection.execute_wrappers:
connection.execute_wrappers.append(query_wrapper_select_for_update)
@@ -1,133 +0,0 @@
#
# 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/>.
#
#
# backport from Django 5.2 (django/django/template/library.py)
#
# TODO: remove once we upgrade to Django 5.2
from functools import wraps
from inspect import getfullargspec, unwrap
from django.template.exceptions import TemplateSyntaxError
from django.template.library import SimpleNode, parse_bits
class SimpleBlockNode(SimpleNode):
def __init__(self, nodelist, *args, **kwargs):
super().__init__(*args, **kwargs)
self.nodelist = nodelist
def get_resolved_arguments(self, context):
resolved_args, resolved_kwargs = super().get_resolved_arguments(context)
# Restore the "content" argument.
# It will move depending on whether takes_context was passed.
resolved_args.insert(
1 if self.takes_context else 0, self.nodelist.render(context)
)
return resolved_args, resolved_kwargs
def register_simple_block_tag(library, func=None, takes_context=None, name=None, end_name=None):
"""
Register a callable as a compiled block template tag. Example:
@register_simple_block_tag(register)
def hello(content):
return 'world'
"""
def dec(func):
nonlocal end_name
(
params,
varargs,
varkw,
defaults,
kwonly,
kwonly_defaults,
_,
) = getfullargspec(unwrap(func))
function_name = name or func.__name__
if end_name is None:
end_name = f"end{function_name}"
@wraps(func)
def compile_func(parser, token):
tag_params = params.copy()
if takes_context:
if len(tag_params) >= 2 and tag_params[1] == "content":
del tag_params[1]
else:
raise TemplateSyntaxError(
f"{function_name!r} is decorated with takes_context=True so"
" it must have a first argument of 'context' and a second "
"argument of 'content'"
)
elif tag_params and tag_params[0] == "content":
del tag_params[0]
else:
raise TemplateSyntaxError(
f"'{function_name}' must have a first argument of 'content'"
)
bits = token.split_contents()[1:]
target_var = None
if len(bits) >= 2 and bits[-2] == "as":
target_var = bits[-1]
bits = bits[:-2]
nodelist = parser.parse((end_name,))
parser.delete_first_token()
args, kwargs = parse_bits(
parser,
bits,
tag_params,
varargs,
varkw,
defaults,
kwonly,
kwonly_defaults,
takes_context,
function_name,
)
return SimpleBlockNode(
nodelist, func, takes_context, args, kwargs, target_var
)
library.tag(function_name, compile_func)
return func
if func is None:
# @register.simple_block_tag(...)
return dec
elif callable(func):
# @register.simple_block_tag
return dec(func)
else:
raise ValueError("Invalid arguments provided to simple_block_tag")
+71 -29
View File
@@ -55,13 +55,14 @@ from django.utils.safestring import mark_safe
from django.utils.timezone import now
from django.utils.translation import gettext, gettext_lazy as _, pgettext
from django_countries import countries
from phonenumber_field.formfields import PhoneNumberField
from text_unidecode import unidecode
from pretix import __version__
from pretix.base.decimal import round_decimal
from pretix.base.forms import SecretKeySettingsField
from pretix.base.forms.questions import (
guess_country, guess_country_from_request,
WrappedPhoneNumberPrefixWidget, guess_country, guess_country_from_request,
)
from pretix.base.models import (
Event, InvoiceAddress, Order, OrderPayment, OrderRefund, Quota,
@@ -116,7 +117,7 @@ logger = logging.getLogger('pretix.plugins.stripe')
# - Stablecoins and Crypto: ✗
# - Kakao Pay: ✗
# - Naver Pay: ✗
# - MB Way: ✗
# - MB Way: ✓
# - Satis Pay: ✗
# - WeChat Pay: ✓
# - PAYCO: ✗
@@ -537,6 +538,14 @@ class StripeSettingsHolder(BasePaymentProvider):
'before they work properly.'),
required=False,
)),
('method_mb_way',
forms.BooleanField(
label=_('MB WAY'),
disabled=self.event.currency not in 'EUR',
help_text=_('Some payment methods might need to be enabled in the settings of your Stripe account '
'before they work properly.'),
required=False,
)),
] + extra_fields + list(super().settings_form_fields.items()) + moto_settings
)
if not self.settings.connect_client_id or self.settings.secret_key:
@@ -1161,33 +1170,6 @@ class StripeCC(StripeMethod):
}
return template.render(ctx)
def _migrate_session(self, request):
# todo: remove after pretix 2023.8 was released
keymap = {
'payment_stripe_payment_method_id': 'payment_stripe_card_payment_method_id',
'payment_stripe_brand': 'payment_stripe_card_brand',
'payment_stripe_last4': 'payment_stripe_card_last4',
}
for old, new in keymap.items():
if old in request.session:
request.session[new] = request.session[old]
del request.session[old]
def checkout_prepare(self, request, cart):
self._migrate_session(request)
request.session['payment_stripe_card_brand'] = request.POST.get('stripe_card_brand', '')
request.session['payment_stripe_card_last4'] = request.POST.get('stripe_card_last4', '')
return super().checkout_prepare(request, cart)
def payment_is_valid_session(self, request):
self._migrate_session(request)
return super().payment_is_valid_session(request)
def _handle_payment_intent(self, request, payment, intent=None):
self._migrate_session(request)
return super()._handle_payment_intent(request, payment, intent)
def is_moto(self, request, payment=None) -> bool:
# We don't have a payment yet when checking if we should display the MOTO-flag
# However, before we execute the payment, we absolutely have to check if the request-SalesChannel as well as the
@@ -1974,3 +1956,63 @@ class StripeWero(StripeRedirectMethod):
'This payment method is available to European online banking users, whose banking institutions support WERO '
'either through their native banking apps or through the WERO wallet app. Please have you app ready.'
)
class StripeRedirectWithPhoneNumberMethod(StripeRedirectMethod):
def payment_form_render(self, request) -> str:
template = get_template('pretixplugins/stripe/checkout_payment_form_simple.html')
ctx = {
'request': request,
'event': self.event,
'settings': self.settings,
'explanation': self.explanation,
'form': self.payment_form(request)
}
return template.render(ctx)
@property
def payment_form_fields(self):
return OrderedDict([
('phone', PhoneNumberField(
label=_('Phone'),
required=True,
widget=WrappedPhoneNumberPrefixWidget()
)),
])
def execute_payment(self, request: HttpRequest, payment: OrderPayment):
try:
return super().execute_payment(request, payment)
finally:
if f'payment_stripe_{self.method}_phone' in request.session:
del request.session[f'payment_stripe_{self.method}_phone']
def checkout_prepare(self, request, cart):
form = self.payment_form(request)
if form.is_valid():
request.session[f"payment_stripe_{self.method}_payment_method_id"] = None
request.session[f'payment_stripe_{self.method}_phone'] = form.cleaned_data['phone'].as_e164
return True
return False
def _payment_intent_kwargs(self, request, payment):
breakpoint()
return {
"payment_method_data": {
"type": self.method,
"billing_details": {
"phone": request.session.get(f"payment_stripe_{self.method}_phone")
}
}
}
class StripeMBWay(StripeRedirectWithPhoneNumberMethod):
identifier = 'stripe_mb_way'
verbose_name = _('MB WAY via Stripe')
public_name = 'MB WAY'
method = 'mb_way'
confirmation_method = 'automatic'
explanation = _(
'This payment method is available to users of the MB WAY App in Portugal. Please have your app ready.'
)
+2 -2
View File
@@ -45,7 +45,7 @@ from pretix.presale.signals import html_head, process_response
def register_payment_provider(sender, **kwargs):
from .payment import (
StripeAffirm, StripeAlipay, StripeBancontact, StripeCC, StripeEPS,
StripeGiropay, StripeIdeal, StripeKlarna, StripeMobilePay,
StripeGiropay, StripeIdeal, StripeKlarna, StripeMBWay, StripeMobilePay,
StripeMultibanco, StripePayByBank, StripePayPal, StripePromptPay,
StripePrzelewy24, StripeRevolutPay, StripeSEPADirectDebit,
StripeSettingsHolder, StripeSofort, StripeSwish, StripeTwint,
@@ -56,7 +56,7 @@ def register_payment_provider(sender, **kwargs):
StripeSettingsHolder, StripeCC, StripeGiropay, StripeIdeal, StripeAlipay, StripeBancontact,
StripeSofort, StripeEPS, StripeMultibanco, StripePayByBank, StripePrzelewy24, StripePromptPay, StripeRevolutPay,
StripeWeChatPay, StripeSEPADirectDebit, StripeAffirm, StripeKlarna, StripePayPal, StripeSwish,
StripeTwint, StripeMobilePay, StripeWero
StripeTwint, StripeMobilePay, StripeWero, StripeMBWay
]
@@ -1,4 +1,5 @@
import type { I18nString, SubEvent } from './i18n'
import type { SubEvent } from './i18n'
import type { LocalizableString } from '@/pretix/static/pretixbase/js/i18n'
const settingsEl = document.getElementById('api-settings')
const { urls } = JSON.parse(settingsEl.textContent || '{}') as { urls: {
@@ -59,8 +60,8 @@ export interface Position {
order: string
positionid: number
canceled?: boolean
item: { id?: number; name: I18nString; internal_name?: string; admission?: boolean }
variation: { id?: number; value: I18nString } | null
item: { id?: number; name: LocalizableString; internal_name?: string; admission?: boolean }
variation: { id?: number; value: LocalizableString } | null
price: string
attendee_name: string
attendee_name_parts: Record<string, string>
@@ -110,8 +111,8 @@ export interface Answer {
export interface AnswerQuestion {
id: number
question: I18nString
help_text?: I18nString
question: LocalizableString
help_text?: LocalizableString
type: string
required: boolean
position: number
@@ -138,12 +139,12 @@ export interface QuestionOption {
id: number
identifier: string
position: number
answer: I18nString
answer: LocalizableString
}
export interface Addon {
item: { name: I18nString; internal_name?: string }
variation: { value: I18nString } | null
item: { name: LocalizableString; internal_name?: string }
variation: { value: LocalizableString } | null
}
export interface CheckinStatusVariation {
@@ -2,7 +2,8 @@
import { ref, computed, nextTick, onMounted, onUnmounted } from 'vue'
import { api } from '../api'
import type { CheckinList, Position, RedeemResponse, CheckinStatus, AnswerQuestion } from '../api'
import { STRINGS, i18nstringLocalize, formatSubevent, formatAnswer } from '../i18n'
import { STRINGS, formatSubevent, formatAnswer } from '../i18n'
import { localize_string } from '@/pretix/static/pretixbase/js/i18n'
import CheckinlistSelect from './checkinlist-select.vue'
import SearchresultItem from './searchresult-item.vue'
@@ -114,9 +115,9 @@ const checkResultAddons = computed(() => {
if (!checkResult.value?.position?.addons) return ''
return checkResult.value.position.addons.map((addon) => {
if (addon.variation) {
return `+ ${addon.item.internal_name || i18nstringLocalize(addon.item.name)} – ${i18nstringLocalize(addon.variation.value)}`
return `+ ${addon.item.internal_name || localize_string(addon.item.name)} – ${localize_string(addon.variation.value)}`
}
return '+ ' + (addon.item.internal_name || i18nstringLocalize(addon.item.name))
return '+ ' + (addon.item.internal_name || localize_string(addon.item.name))
}).join('\n')
})
@@ -125,9 +126,9 @@ const checkResultSubevent = computed(() => formatSubevent(checkResult.value?.pos
const checkResultItemvar = computed(() => {
if (!checkResult.value?.position) return ''
if (checkResult.value.position.variation) {
return `${i18nstringLocalize(checkResult.value.position.item.name)} – ${i18nstringLocalize(checkResult.value.position.variation.value)}`
return `${localize_string(checkResult.value.position.item.name)} – ${localize_string(checkResult.value.position.variation.value)}`
}
return i18nstringLocalize(checkResult.value.position.item.name)
return localize_string(checkResult.value.position.item.name)
})
const checkResultText = computed(() => {
@@ -316,9 +317,9 @@ async function check (
if (!answers.value[q.id.toString()]) {
answers.value[q.id.toString()] = ''
}
;(q as AnswerQuestion).question = i18nstringLocalize(q.question)
;(q as AnswerQuestion).question = localize_string(q.question)
for (const o of q.options) {
;(o as { answer: string }).answer = i18nstringLocalize(o.answer)
;(o as { answer: string }).answer = localize_string(o.answer)
}
}
nextTick(() => {
@@ -410,7 +411,7 @@ onUnmounted(() => {
span(v-for="a in checkResult.position.answers")
span(v-if="a.question.show_during_checkin")
br
strong {{ i18nstringLocalize(a.question.question) }}:
strong {{ localize_string(a.question.question) }}:
| {{ formatAnswer(a.answer, a.question) }}
strong(v-for="t in checkResult.checkin_texts")
br
@@ -1,7 +1,8 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import type { Position } from '../api'
import { STRINGS, i18nstringLocalize, formatSubevent } from '../i18n'
import { STRINGS, formatSubevent } from '../i18n'
import { localize_string } from '@/pretix/static/pretixbase/js/i18n'
const props = defineProps<{
position: Position
@@ -22,9 +23,9 @@ const status = computed(() => {
const itemvar = computed(() => {
if (props.position.variation) {
return `${i18nstringLocalize(props.position.item.name)} – ${i18nstringLocalize(props.position.variation.value)}`
return `${localize_string(props.position.item.name)} – ${localize_string(props.position.variation.value)}`
}
return i18nstringLocalize(props.position.item.name)
return localize_string(props.position.item.name)
})
const subevent = computed(() => formatSubevent(props.position.subevent))
@@ -1,3 +1,6 @@
import { localize_string } from '@/pretix/static/pretixbase/js/i18n'
import '@/pretix/static/pretixbase/js/gettextstub'
const body = document.body
export const timezone = body.dataset.timezone ?? 'UTC'
@@ -9,27 +12,6 @@ export const pretixLocale = body.dataset.pretixlocale ?? 'en'
moment.locale(datetimeLocale)
export function gettext (msgid: string): string {
if (typeof django !== 'undefined' && typeof django.gettext !== 'undefined') {
return django.gettext(msgid)
}
return msgid
}
export function ngettext (singular: string, plural: string, count: number): string {
if (typeof django !== 'undefined' && typeof django.ngettext !== 'undefined') {
return django.ngettext(singular, plural, count)
}
return plural
}
export type I18nString = string | Record<string, string> | null | undefined
export function i18nstringLocalize (obj: I18nString): string {
// external
return i18nstring_localize(obj)
}
export const STRINGS: Record<string, string> = {
'checkinlist.select': gettext('Select a check-in list'),
'checkinlist.none': gettext('No active check-in lists found.'),
@@ -83,7 +65,7 @@ export interface SubEvent {
export function formatSubevent (subevent: SubEvent | null | undefined): string {
if (!subevent) return ''
const name = i18nstringLocalize(subevent.name)
const name = localize_string(subevent.name)
const date = moment.utc(subevent.date_from).tz(timezone).format(datetimeFormat)
return `${name} · ${date}`
}
@@ -26,7 +26,6 @@
data-pretixlocale="{{ request.LANGUAGE_CODE }}" data-timezone="{{ request.event.settings.timezone }}">
<div id="app" data-event-name="{{ request.event.name }}"></div>
{% compress js %}
<script type="text/javascript" src="{% static "pretixbase/js/i18nstring.js" %}"></script>
<script type="text/javascript" src="{% static "moment/moment-with-locales.js" %}"></script>
<script type="text/javascript" src="{% static "moment/moment-timezone-with-data-1970-2030.js" %}"></script>
<script type="text/javascript" src="{% static "jquery/js/jquery-3.6.4.min.js" %}"></script>
+1 -1
View File
@@ -283,7 +283,7 @@ class CartMixin:
'is_ordered': bool(order),
'itemcount': sum(c.count for c in positions if not c.addon_to),
'show_rounding_info': (
self.request.event.settings.tax_rounding == "sum_by_net_only_business" and
self.request.event.settings.tax_rounding in ("sum_by_net_only_business", "sum_by_net_business_else_gross") and
not self.request.event.settings.display_net_prices and
sum(c.price_includes_rounding_correction for c in positions) + sum(f.price_includes_rounding_correction for f in fees)
),
+1
View File
@@ -57,6 +57,7 @@ class WaitingView(EventViewMixin, FormView):
self.request.event,
subevent=self.subevent,
require_seat=None,
base_qs=self.request.event.items.filter(require_voucher=False),
channel=self.request.organizer.sales_channels.get(identifier="web"),
memberships=(
customer.usable_memberships(
@@ -0,0 +1,48 @@
<script setup lang="ts">
import { watchEffect } from 'vue'
defineOptions({
inheritAttrs: false,
})
const props = defineProps<{
placeholders?: Record<string, string>;
locales: Record<string, string>;
errors?: string[];
multiline?: boolean;
}>()
const modelValue = defineModel<Record<string, string> | string>({ default: () => ({}) })
watchEffect(() => {
if (typeof modelValue.value === 'string') {
const oldVal = modelValue.value
modelValue.value = Object.fromEntries(
Object.keys(props.locales).map((x): [string, string] => [x, oldVal]),
)
}
const additionalLocales = new Set(Object.keys(modelValue.value)).difference(new Set(Object.keys(props.locales)))
for (const additionalLocale of additionalLocales) {
delete modelValue.value[additionalLocale]
}
})
</script>
<template lang="pug">
template(v-if="!!modelValue")
div.i18n-form-group
component.form-control(
:is="multiline ? 'textarea' : 'input'"
v-for="(human_readable, locale) in locales"
v-bind="$attrs"
:key="locale"
:lang="locale"
:title="human_readable"
:placeholder="placeholders?.[locale] || human_readable"
:value="modelValue[locale]"
@input="event => modelValue[locale] = event.target.value"
)
template(v-if="!!errors")
.help-block(v-for="error in errors") {{ error }}
</template>
@@ -1,29 +1,29 @@
// The actual gettext implementation is loaded asynchronously with the translation
function gettext (msgid) {
globalThis.gettext = (msgid) => {
if (typeof django !== 'undefined' && typeof django.gettext !== 'undefined') {
return django.gettext(msgid)
}
return msgid
}
function ngettext (singular, plural, count) {
globalThis.ngettext = (singular, plural, count) => {
if (typeof django !== 'undefined' && typeof django.ngettext !== 'undefined') {
return django.ngettext(singular, plural, count)
}
return plural
}
function pgettext (context, msgid) {
globalThis.pgettext = (context, msgid) => {
if (typeof django !== 'undefined' && typeof django.pgettext !== 'undefined') {
return django.pgettext(context, msgid)
}
return msgid
}
function interpolate (fmt, obj, named) {
globalThis.interpolate = (fmt, obj, named) => {
if (named) {
return fmt.replace(/%\(\w+\)s/g, function (match) { return String(obj[match.slice(2, -2)]) })
} else {
return fmt.replace(/%s/g, function (match) { return String(obj.shift()) })
}
}
}
+31
View File
@@ -0,0 +1,31 @@
export type LocalizableString = null | string | Record<string, string>;
export function localize_string(s: LocalizableString, locale?: string): string {
if (typeof s === "string") {
return s;
}
if (s === null) {
return null;
}
if (!locale) {
locale = document.body.attributes["data-pretixlocale"].value;
}
var short_locale = locale.split("-")[0];
if (locale in s) return s[locale];
if (short_locale in s) return s[short_locale];
for (const k of Object.keys(s)) {
if (k.split("-")[0] === short_locale && s[k]) {
return s[k];
}
}
if (s["en"]) return s["en"];
for (const k of Object.keys(s)) {
if (s[k]) {
return s[k];
}
}
}
@@ -1,24 +0,0 @@
function i18nstring_localize (o) {
let locale = document.body.attributes['data-pretixlocale'].value
let short_locale = locale.split('-')[0]
if (o[locale])
return o[locale]
if (o[short_locale])
return o[short_locale]
for (let k of Object.keys(o)) {
if (k.split('-')[0] === short_locale && o[k]) {
return o[k]
}
}
if (o['en'])
return o['en']
for (let k of Object.keys(o)) {
if (o[k]) {
return o[k]
}
}
}
@@ -1,5 +1,3 @@
/* global gettext, pgettext */
export const TEXTS = {
and: gettext('All of the conditions below (AND)'),
or: gettext('At least one of the conditions below (OR)'),
+11 -1
View File
@@ -40,7 +40,7 @@ from django.utils.timezone import now
from django_scopes import scopes_disabled
from rest_framework.test import APIClient
from pretix.base.models import Device, Event, Organizer, Team, User
from pretix.base.models import Device, Event, Gate, Organizer, Team, User
from pretix.base.models.devices import generate_api_token
@@ -132,6 +132,16 @@ def device(organizer):
)
@pytest.fixture
@scopes_disabled()
def gate(organizer):
return Gate.objects.create(
organizer=organizer,
name='Entry',
identifier='entry'
)
@pytest.fixture
def user():
return User.objects.create_user('dummy@dummy.dummy', 'dummy')
+96
View File
@@ -0,0 +1,96 @@
#
# 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_scopes import scopes_disabled
from pretix.base.models import Gate
TEST_RES = {
"name": "Entry",
"identifier": "entry"
}
@pytest.mark.django_db
def test_gate_list(token_client, organizer, gate):
res = dict(TEST_RES)
resp = token_client.get('/api/v1/organizers/{}/gates/'.format(organizer.slug))
assert resp.status_code == 200
gate.refresh_from_db()
res["id"] = gate.pk
assert [res] == resp.data['results']
@pytest.mark.django_db
def test_gate_detail(token_client, organizer, gate):
res = dict(TEST_RES)
resp = token_client.get('/api/v1/organizers/{}/gates/{}/'.format(organizer.slug, gate.id))
assert resp.status_code == 200
gate.refresh_from_db()
res["id"] = gate.pk
assert res == resp.data
TEST_GATE_CREATE_PAYLOAD = {
"name": "Second entry",
"identifier": "entry_2"
}
@pytest.mark.django_db
def test_gate_create(token_client, organizer):
resp = token_client.post(
'/api/v1/organizers/{}/gates/'.format(organizer.slug),
TEST_GATE_CREATE_PAYLOAD,
format='json'
)
assert resp.status_code == 201
with scopes_disabled():
g = Gate.objects.get(id=resp.data['id'])
assert g.name == TEST_GATE_CREATE_PAYLOAD.get('name')
assert g.identifier == TEST_GATE_CREATE_PAYLOAD.get('identifier')
@pytest.mark.django_db
def test_gate_update(token_client, organizer, gate):
resp = token_client.patch(
'/api/v1/organizers/{}/gates/{}/'.format(organizer.slug, gate.id),
{
'name': 'Main entry'
},
format='json'
)
assert resp.status_code == 200
gate.refresh_from_db()
assert gate.name == 'Main entry'
assert gate.identifier == TEST_RES.get('identifier')
@pytest.mark.django_db
def test_gate_delete(token_client, organizer, gate):
resp = token_client.delete(
'/api/v1/organizers/{}/gates/{}/'.format(organizer.slug, gate.id),
)
assert resp.status_code == 204
with scopes_disabled():
assert organizer.gates.count() == 0
+242 -1
View File
@@ -1012,6 +1012,58 @@ def test_order_create_tax_rules(token_client, organizer, event, item, quota, que
assert pos.tax_rule == taxrule
@pytest.mark.django_db
def test_order_create_tax_rule_explicit(token_client, organizer, event, item, quota, question, taxrule):
item.tax_rule = None
item.save()
res = copy.deepcopy(ORDER_CREATE_PAYLOAD)
res['fees'][0]['tax_rule'] = taxrule.pk
res['positions'][0]['item'] = item.pk
res['positions'][0]['tax_rule'] = taxrule.pk
res['positions'][0]['answers'][0]['question'] = question.pk
resp = token_client.post(
'/api/v1/organizers/{}/events/{}/orders/'.format(
organizer.slug, event.slug
), format='json', data=res
)
assert resp.status_code == 201
with scopes_disabled():
o = Order.objects.get(code=resp.data['code'])
pos = o.positions.first()
assert pos.item == item
assert pos.tax_rate == Decimal('19.00')
assert pos.tax_value == Decimal('3.67')
assert pos.tax_rule == taxrule
assert pos.tax_code == "S/standard"
@pytest.mark.django_db
def test_order_create_tax_rule_custom_rate_and_code(token_client, organizer, event, item, quota, question, taxrule):
item.tax_rule = None
item.save()
res = copy.deepcopy(ORDER_CREATE_PAYLOAD)
res['fees'][0]['tax_rule'] = taxrule.pk
res['positions'][0]['item'] = item.pk
res['positions'][0]['tax_rule'] = taxrule.pk
res['positions'][0]['tax_code'] = 'S/reduced'
res['positions'][0]['tax_rate'] = "7.00"
res['positions'][0]['answers'][0]['question'] = question.pk
resp = token_client.post(
'/api/v1/organizers/{}/events/{}/orders/'.format(
organizer.slug, event.slug
), format='json', data=res
)
assert resp.status_code == 201
with scopes_disabled():
o = Order.objects.get(code=resp.data['code'])
pos = o.positions.first()
assert pos.item == item
assert pos.tax_rate == Decimal('7.00')
assert pos.tax_value == Decimal('1.50')
assert pos.tax_rule == taxrule
assert pos.tax_code == "S/reduced"
@pytest.mark.django_db
def test_order_create_fee_type_validation(token_client, organizer, event, item, quota, question):
res = copy.deepcopy(ORDER_CREATE_PAYLOAD)
@@ -1107,6 +1159,75 @@ def test_order_create_fee_with_auto_tax(token_client, organizer, event, item, qu
assert o.total == Decimal('25.30')
@pytest.mark.django_db
def test_order_create_fee_with_explicit_tax_and_percentage(token_client, organizer, event, item, quota, question, taxrule):
res = copy.deepcopy(ORDER_CREATE_PAYLOAD)
res['fees'][0]['tax_rate'] = '7.00'
res['fees'][0]['tax_rule'] = taxrule.pk
res['fees'][0]['_split_taxes_like_products'] = False
res['fees'][0]['_treat_value_as_percentage'] = True
res['fees'][0]['value'] = '10.00'
res['positions'][0]['item'] = item.pk
res['positions'][0]['answers'][0]['question'] = question.pk
item.tax_rule = taxrule
item.save()
resp = token_client.post(
'/api/v1/organizers/{}/events/{}/orders/'.format(
organizer.slug, event.slug
), format='json', data=res
)
assert resp.status_code == 201
with scopes_disabled():
o = Order.objects.get(code=resp.data['code'])
fee = o.fees.first()
assert fee.value == Decimal('2.30')
assert fee.tax_rate == Decimal('7.00')
assert fee.tax_value == Decimal('0.15')
assert o.total == Decimal('25.30')
@pytest.mark.django_db
def test_order_create_fee_with_explicit_tax_and_split_requested(token_client, organizer, event, item, quota, question, taxrule):
res = copy.deepcopy(ORDER_CREATE_PAYLOAD)
res['fees'][0]['tax_rate'] = '7.00'
res['fees'][0]['tax_rule'] = taxrule.pk
res['fees'][0]['_split_taxes_like_products'] = True
res['fees'][0]['_treat_value_as_percentage'] = True
res['fees'][0]['value'] = '10.00'
res['positions'][0]['item'] = item.pk
res['positions'][0]['answers'][0]['question'] = question.pk
item.tax_rule = taxrule
item.save()
resp = token_client.post(
'/api/v1/organizers/{}/events/{}/orders/'.format(
organizer.slug, event.slug
), format='json', data=res
)
assert resp.status_code == 400
assert resp.data == {
'fees': [{'tax_rate': ['You cannot ask for the value to be distributed over tax rates if you already set the tax rate or computed taxes.']}],
}
res['fees'][0]['tax_rate'] = '7.00'
res['fees'][0]['tax_value'] = '1.50'
res['fees'][0]['tax_rule'] = taxrule.pk
res['fees'][0]['_treat_value_as_percentage'] = True
res['fees'][0]['value'] = '10.00'
res['positions'][0]['item'] = item.pk
res['positions'][0]['answers'][0]['question'] = question.pk
item.tax_rule = taxrule
item.save()
resp = token_client.post(
'/api/v1/organizers/{}/events/{}/orders/'.format(
organizer.slug, event.slug
), format='json', data=res
)
assert resp.status_code == 400
assert resp.data == {
'fees': [{'tax_value': ['You cannot ask for the value to be treated as a percentage if you already computed taxes.']}],
}
@pytest.mark.django_db
def test_order_create_negative_fee_with_auto_tax(token_client, organizer, event, item, quota, question, taxrule):
res = copy.deepcopy(ORDER_CREATE_PAYLOAD)
@@ -1136,6 +1257,7 @@ def test_order_create_tax_rule_wrong_event(token_client, organizer, event, item,
res = copy.deepcopy(ORDER_CREATE_PAYLOAD)
res['fees'][0]['tax_rule'] = taxrule2.pk
res['positions'][0]['item'] = item.pk
res['positions'][0]['tax_rule'] = taxrule2.pk
res['positions'][0]['answers'][0]['question'] = question.pk
resp = token_client.post(
'/api/v1/organizers/{}/events/{}/orders/'.format(
@@ -1143,7 +1265,10 @@ def test_order_create_tax_rule_wrong_event(token_client, organizer, event, item,
), format='json', data=res
)
assert resp.status_code == 400
assert resp.data == {'fees': [{'tax_rule': ['The specified tax rate does not belong to this event.']}]}
assert resp.data == {
'positions': [{'tax_rule': ['The specified tax rule does not belong to this event.']}],
'fees': [{'tax_rule': ['The specified tax rule does not belong to this event.']}],
}
@pytest.mark.django_db
@@ -3693,3 +3818,119 @@ def test_order_create_use_gift_card_invalid_secret(token_client, organizer, even
assert o.payments.count() == 2
assert o.payments.all()[0].state == OrderPayment.PAYMENT_STATE_FAILED
assert o.payments.all()[1].state == OrderPayment.PAYMENT_STATE_CONFIRMED
@pytest.mark.django_db
@pytest.mark.parametrize("rounding_mode,data,error", [
("line", {"tax_value": "2.40"}, "Tax value 2.40 in position 1 does not match backend computation of 2.39."),
("line", {"tax_value": "2.39"}, None),
("line", {"price_includes_rounding_correction": "0.01"}, "Price rounding 0.01 in position 1 does not match backend computation of 0.00."),
("line", {"tax_value_includes_rounding_correction": "0.01"}, "Tax rounding 0.01 in position 1 does not match backend computation of 0.00."),
("sum_by_net",
{"tax_value": "2.39"},
"Tax value 2.39 in position 1 does not match backend computation of 2.40."),
("sum_by_net",
{"tax_value": "2.40", "price": "15.01", "price_includes_rounding_correction": "0.01"},
None),
("sum_by_net",
{"tax_value": "2.40", "price": "15.00", "price_includes_rounding_correction": "0.00"},
"Price rounding 0.00 in position 1 does not match backend computation of 0.01."),
("sum_by_net",
{"tax_value": "2.40", "price": "15.01", "price_includes_rounding_correction": "0.01", "tax_value_includes_rounding_correction": "0.00"},
"Tax rounding 0.00 in position 1 does not match backend computation of 0.01."),
])
def test_order_tax_match_validation(token_client, organizer, event, item, quota, question, taxrule,
rounding_mode, data, error):
res = copy.deepcopy(ORDER_CREATE_PAYLOAD)
del res['fees']
res['tax_rounding_mode'] = rounding_mode
res['positions'][0]['item'] = item.pk
res['positions'][0]['price'] = "15.00"
res['positions'][0]['tax_rule'] = taxrule.pk
res['positions'][0]['answers'][0]['question'] = question.pk
res['positions'][0].update(data)
resp = token_client.post(
'/api/v1/organizers/{}/events/{}/orders/'.format(
organizer.slug, event.slug
), format='json', data=res
)
if error:
assert resp.status_code == 400
assert resp.data == [error]
else:
assert resp.status_code == 201
@pytest.mark.django_db
@pytest.mark.parametrize("rounding_mode,data,error", [
("line", {"tax_value": "1.61"}, "Tax value 1.61 in fee does not match backend computation of 1.60."),
("line", {"tax_value": "1.60"}, None),
("line", {"value_includes_rounding_correction": "0.01"},
"Price rounding 0.01 in fee does not match backend computation of 0.00."),
("line", {"tax_value_includes_rounding_correction": "0.01"},
"Tax rounding 0.01 in fee does not match backend computation of 0.00."),
("sum_by_net",
{"tax_value": "1.60"},
"Tax value 1.60 in fee does not match backend computation of 1.59."),
("sum_by_net",
{"tax_value": "1.59", "value": "9.99", "value_includes_rounding_correction": "-0.01"},
None),
("sum_by_net",
{"tax_value": "1.59", "value": "10.00", "value_includes_rounding_correction": "0.00"},
"Price rounding 0.00 in fee does not match backend computation of -0.01."),
("sum_by_net",
{"tax_value": "1.59", "value": "9.99", "value_includes_rounding_correction": "-0.01",
"tax_value_includes_rounding_correction": "0.00"},
"Tax rounding 0.00 in fee does not match backend computation of -0.01."),
])
def test_order_tax_match_validation_of_fee(token_client, organizer, event, item, quota, question, taxrule,
rounding_mode, data, error):
res = copy.deepcopy(ORDER_CREATE_PAYLOAD)
res['tax_rounding_mode'] = rounding_mode
res['positions'][0]['item'] = item.pk
res['positions'][0]['price'] = "5.00"
res['positions'][0]['tax_rule'] = taxrule.pk
res['positions'][0]['answers'][0]['question'] = question.pk
res['fees'][0]['value'] = "10.00"
res['fees'][0]['tax_rule'] = taxrule.pk
res['fees'][0].update(data)
resp = token_client.post(
'/api/v1/organizers/{}/events/{}/orders/'.format(
organizer.slug, event.slug
), format='json', data=res
)
if error:
assert resp.status_code == 400
assert resp.data == [error]
else:
assert resp.status_code == 201
@pytest.mark.django_db
def test_order_expect_total(token_client, organizer, event, item, quota, question, taxrule):
# Force a rounding difference to make sure it's the last step of total computation that is compared
res = copy.deepcopy(ORDER_CREATE_PAYLOAD)
del res['fees']
res['tax_rounding_mode'] = "sum_by_net"
res['positions'][0]['item'] = item.pk
res['positions'][0]['price'] = "15.00"
res['positions'][0]['tax_rule'] = taxrule.pk
res['positions'][0]['answers'][0]['question'] = question.pk
res['total'] = "15.00"
resp = token_client.post(
'/api/v1/organizers/{}/events/{}/orders/'.format(
organizer.slug, event.slug
), format='json', data=res
)
assert resp.status_code == 400
assert resp.data == {
'total': ['Order total of 15.00 does not match backend computation of 15.01.']
}
res['total'] = "15.01"
resp = token_client.post(
'/api/v1/organizers/{}/events/{}/orders/'.format(
organizer.slug, event.slug
), format='json', data=res
)
assert resp.status_code == 201
+13
View File
@@ -255,6 +255,12 @@ org_permission_sub_urls = [
('get', 'organizer.devices:read', 'devices/1/', 404),
('put', 'organizer.devices:write', 'devices/1/', 404),
('patch', 'organizer.devices:write', 'devices/1/', 404),
('get', 'organizer.devices:read', 'gates/', 200),
('post', 'organizer.devices:write', 'gates/', 400),
('get', 'organizer.devices:read', 'gates/1/', 404),
('put', 'organizer.devices:write', 'gates/1/', 404),
('patch', 'organizer.devices:write', 'gates/1/', 404),
('delete', 'organizer.devices:write', 'gates/1/', 404),
('get', 'organizer.teams:write', 'teams/', 200),
('post', 'organizer.teams:write', 'teams/', 400),
('get', 'organizer.teams:write', 'teams/{team_id}/', 200),
@@ -320,6 +326,13 @@ def test_organizer_not_allowed_device(device_client, organizer):
assert resp.status_code == 403
@pytest.mark.django_db
def test_organizer_not_allowed_gate(token_client, organizer):
o2 = Organizer.objects.create(slug='o2', name='Organizer 2')
resp = token_client.get('/api/v1/organizers/{}/gates/'.format(o2.slug))
assert resp.status_code == 403
@pytest.mark.django_db
def test_organizer_not_existing(token_client, organizer):
resp = token_client.get('/api/v1/organizers/{}/events/'.format('o2'))
+2
View File
@@ -1798,6 +1798,7 @@ class OrderChangeManagerTests(BaseOrderChangeManagerTestCase, TestCase):
assert self.op1.item == self.shirt
assert self.op1.price == Decimal('23.00')
assert self.op1.tax_rate == self.shirt.tax_rule.rate
assert self.op1.tax_code == self.shirt.tax_rule.code
assert round_decimal(self.op1.price * (1 - 100 / (100 + self.op1.tax_rate))) == self.op1.tax_value
assert self.order.total == self.op1.price + self.op2.price
@@ -1811,6 +1812,7 @@ class OrderChangeManagerTests(BaseOrderChangeManagerTestCase, TestCase):
assert self.op1.item == self.shirt
assert self.op1.price == Decimal('12.00')
assert self.op1.tax_rate == self.shirt.tax_rule.rate
assert self.op1.tax_code == self.shirt.tax_rule.code
assert round_decimal(self.op1.price * (1 - 100 / (100 + self.op1.tax_rate))) == self.op1.tax_value
assert self.order.total == self.op1.price + self.op2.price
+57 -1
View File
@@ -73,6 +73,14 @@ def _validate_sample_lines(sample_lines, rounding_mode):
assert sum(line.price for line in sample_lines) == Decimal("500.00")
assert sum(line.tax_value for line in sample_lines) == Decimal("79.83")
assert sum(line.price - line.tax_value for line in sample_lines) == Decimal("420.17")
elif rounding_mode == "sum_by_gross":
for line in sample_lines:
assert line.price == Decimal("100.00")
# net price may vary
assert line.tax_rate == Decimal("19.00")
assert sum(line.price for line in sample_lines) == Decimal("500.00")
assert sum(line.tax_value for line in sample_lines) == Decimal("79.83")
assert sum(line.price - line.tax_value for line in sample_lines) == Decimal("420.17")
@pytest.mark.django_db
@@ -86,16 +94,22 @@ def test_simple_case_by_net(sample_lines):
@pytest.mark.django_db
def test_simple_case_by_gross(sample_lines):
def test_simple_case_net_by_gross(sample_lines):
_validate_sample_lines(sample_lines, "sum_by_net_keep_gross")
@pytest.mark.django_db
def test_simple_case_by_gross(sample_lines):
_validate_sample_lines(sample_lines, "sum_by_gross")
@pytest.mark.django_db
def test_simple_case_switch_rounding(sample_lines):
_validate_sample_lines(sample_lines, "sum_by_net")
_validate_sample_lines(sample_lines, "sum_by_net_keep_gross")
_validate_sample_lines(sample_lines, "line")
_validate_sample_lines(sample_lines, "sum_by_net")
_validate_sample_lines(sample_lines, "sum_by_gross")
@pytest.mark.django_db
@@ -134,6 +148,24 @@ def test_revert_net_keep_gross_rounding_to_single_line(sample_lines):
assert l.tax_rate == Decimal("19.00")
@pytest.mark.django_db
def test_revert_gross_rounding_to_single_line(sample_lines):
l = OrderPosition(
price=Decimal("100.00"),
price_includes_rounding_correction=Decimal("0.00"),
tax_value=Decimal("15.96"),
tax_value_includes_rounding_correction=Decimal("-0.01"),
tax_rate=Decimal("19.00"),
tax_code="S",
)
apply_rounding("sum_by_gross", None, "EUR", [l])
assert l.price == Decimal("100.00")
assert l.price_includes_rounding_correction == Decimal("0.00")
assert l.tax_value == Decimal("15.97")
assert l.tax_value_includes_rounding_correction == Decimal("0.00")
assert l.tax_rate == Decimal("19.00")
@pytest.mark.django_db
@pytest.mark.parametrize("rounding_mode", [
"sum_by_net",
@@ -152,6 +184,24 @@ def test_rounding_of_impossible_gross_price(rounding_mode):
assert l.tax_rate == Decimal("7.00")
@pytest.mark.django_db
@pytest.mark.parametrize("rounding_mode", [
"sum_by_gross",
"line",
])
def test_rounding_of_impossible_gross_price_possible_when_not_rounding_by_net(rounding_mode):
l = OrderPosition(
price=Decimal("23.00"),
)
l._calculate_tax(tax_rule=TaxRule(rate=Decimal("7.00")), invoice_address=InvoiceAddress())
apply_rounding(rounding_mode, None, "EUR", [l])
assert l.price == Decimal("23.00")
assert l.price_includes_rounding_correction == Decimal("0.00")
assert l.tax_value == Decimal("1.50")
assert l.tax_value_includes_rounding_correction == Decimal("0.00")
assert l.tax_rate == Decimal("7.00")
@pytest.mark.django_db
def test_round_down():
lines = [OrderPosition(
@@ -262,3 +312,9 @@ def test_only_business():
apply_rounding("sum_by_net_only_business", InvoiceAddress(is_business=True), "EUR", lines)
assert sum(l.price for l in lines) == Decimal("499.98")
apply_rounding("sum_by_net_business_else_gross", None, "EUR", lines)
assert sum(l.price for l in lines) == Decimal("500.00")
apply_rounding("sum_by_net_business_else_gross", InvoiceAddress(is_business=True), "EUR", lines)
assert sum(l.price for l in lines) == Decimal("499.98")
+29 -2
View File
@@ -1307,7 +1307,20 @@ class SubEventsTest(SoupTest):
for se in [self.subevent1, self.subevent2]:
assert se.checkinlist_set.count() == 1
def test_edit_bulk_lists_keep_mixed(self):
def test_edit_bulk_lists_keep_mixed_if_checked_in(self):
with scopes_disabled():
self.subevent1.checkinlist_set.create(event=self.event1, name="C1")
cl = self.subevent2.checkinlist_set.create(event=self.event1, name="C2")
cl.checkins.create(
successful=False,
)
doc = self.post_doc('/control/event/ccc/30c3/subevents/bulk_edit', {
'__ALL': 'on',
}, follow=True)
fields = extract_form_fields(doc)
assert 'checkinlist_set-TOTAL_FORMS' not in fields
def test_edit_bulk_lists_replace_mixed_if_unused(self):
with scopes_disabled():
self.subevent1.checkinlist_set.create(event=self.event1, name="C1")
self.subevent2.checkinlist_set.create(event=self.event1, name="C2")
@@ -1315,4 +1328,18 @@ class SubEventsTest(SoupTest):
'__ALL': 'on',
}, follow=True)
fields = extract_form_fields(doc)
assert 'checkinlist_set-TOTAL_FORMS' not in fields
fields.update({
'_bulk': ['__checkinlists'],
'checkinlist_set-TOTAL_FORMS': '1',
'checkinlist_set-INITIAL_FORMS': '0',
'checkinlist_set-MIN_NUM_FORMS': '0',
'checkinlist_set-MAX_NUM_FORMS': '1000',
'checkinlist_set-0-name': 'Default',
'checkinlist_set-0-all_products': 'on',
})
doc = self.post_doc('/control/event/ccc/30c3/subevents/bulk_edit', fields, follow=True)
assert doc.select(".alert-success")
with scopes_disabled():
assert self.subevent1.checkinlist_set.get().name == "Default"
assert self.subevent2.checkinlist_set.get().name == "Default"
-94
View File
@@ -1,94 +0,0 @@
#
# 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.conf import settings
from django.test import override_settings
from django_scopes import scope, scopes_disabled
from pretix.base.models import Organizer
from pretix.base.models.orders import Order, OrderPayment
from pretix.helpers import OF_SELF, UnsafeSQLQueryException
@pytest.fixture
def pg_only():
if 'postgres' not in settings.DATABASES['default']['ENGINE']:
pytest.skip("Test only runs on PostgreSQL")
@pytest.fixture
def organizer():
return Organizer.objects.create(name="Dummy", slug="dummy")
@pytest.mark.django_db
@override_settings(DEBUG=True)
def test_fail_on_debug(pg_only, organizer):
with scope(organizer=organizer):
with pytest.raises(UnsafeSQLQueryException):
list(OrderPayment.objects.select_for_update()) # join added by django-scopes
with pytest.raises(UnsafeSQLQueryException):
list(Order.objects.select_related("event").select_for_update())
with pytest.raises(UnsafeSQLQueryException):
list(Order.objects.filter(event__slug="test").select_for_update())
with pytest.raises(UnsafeSQLQueryException):
list(Order.objects.filter(event__slug="test").select_for_update(no_key=True))
with pytest.raises(UnsafeSQLQueryException):
list(Order.objects.filter(event__slug="test").select_for_update(nowait=True))
with pytest.raises(UnsafeSQLQueryException):
list(Order.objects.filter(event__slug="test").select_for_update(skip_locked=True))
with pytest.raises(UnsafeSQLQueryException):
list(Order.objects.filter(event__slug="test").select_for_update(nowait=True, no_key=True))
with pytest.raises(UnsafeSQLQueryException):
list(Order.objects.filter(event__slug="test").select_for_update(skip_locked=True, no_key=True))
@pytest.mark.django_db
@override_settings(DEBUG=True)
def test_ok_with_of(pg_only, organizer):
with scope(organizer=organizer):
list(OrderPayment.objects.select_for_update(of=OF_SELF)) # join added by django-scopes
list(Order.objects.select_related("event").select_for_update(of=OF_SELF))
list(Order.objects.filter(event__slug="test").select_for_update(of=OF_SELF))
list(Order.objects.filter(event__slug="test").select_for_update(of=OF_SELF, no_key=True))
list(Order.objects.filter(event__slug="test").select_for_update(of=OF_SELF, nowait=True))
list(Order.objects.filter(event__slug="test").select_for_update(of=OF_SELF, skip_locked=True))
list(Order.objects.filter(event__slug="test").select_for_update(of=OF_SELF, nowait=True, no_key=True))
list(Order.objects.filter(event__slug="test").select_for_update(of=OF_SELF, skip_locked=True, no_key=True))
@pytest.mark.django_db
@override_settings(DEBUG=True)
def test_ok_without_join(pg_only, organizer):
with scope(organizer=organizer):
assert list(Order.objects.select_for_update()) == []
with scopes_disabled():
assert list(OrderPayment.objects.select_for_update()) == []
@pytest.mark.django_db
@override_settings(DEBUG=False)
def test_fail_silently_without_debug(pg_only, organizer):
with scope(organizer=organizer):
list(OrderPayment.objects.select_for_update()) # join added by django-scopes
list(Order.objects.select_related("event").select_for_update())
+39
View File
@@ -168,6 +168,45 @@ class CartTest(CartTestMixin, TestCase):
self.assertIsNone(objs[0].variation)
self.assertEqual(objs[0].price, 23)
def _test_simple_tax_code(self, tr):
self.ticket.tax_rule = tr
self.ticket.save()
response = self.client.post('/%s/%s/cart/add' % (self.orga.slug, self.event.slug), {
'item_%d' % self.ticket.id: '1'
}, follow=True)
self.assertRedirects(response, '/%s/%s/?require_cookie=true' % (self.orga.slug, self.event.slug),
target_status_code=200)
doc = BeautifulSoup(response.rendered_content, "lxml")
self.assertIn('Early-bird', doc.select('.cart .cart-row')[0].select('strong')[0].text)
self.assertIn('1', doc.select('.cart .cart-row')[0].select('.count')[0].text)
self.assertIn('23', doc.select('.cart .cart-row')[0].select('.price')[0].text)
self.assertIn('23', doc.select('.cart .cart-row')[0].select('.price')[1].text)
with scopes_disabled():
objs = list(CartPosition.objects.filter(cart_id=self.session_key, event=self.event))
self.assertEqual(len(objs), 1)
self.assertEqual(objs[0].item, self.ticket)
self.assertIsNone(objs[0].variation)
self.assertEqual(objs[0].price, 23)
assert objs[0].tax_code == tr.code
assert objs[0].tax_rate == tr.rate
def test_simple_tax_standard(self):
tr_standard = self.event.tax_rules.create(
name='VAT',
rate=Decimal('19.00'),
code="S/standard",
)
self._test_simple_tax_code(tr_standard)
def test_simple_tax_outside(self):
tr_o = self.event.tax_rules.create(
name='VAT',
rate=Decimal('0'),
code="O",
)
self._test_simple_tax_code(tr_o)
def test_widget_data_post(self):
self.event.settings.attendee_names_asked = True
self.event.settings.attendee_emails_asked = True
+3 -1
View File
@@ -7,7 +7,9 @@
],
"compilerOptions": {
"baseUrl": ".",
"paths": {},
"paths": {
"@/*": ["./src/*"],
},
"strict": false,
"allowJs": true,
"checkJs": true,
+6 -3
View File
@@ -25,6 +25,9 @@ export default defineConfig({
// Pin shared deps to pretix's node_modules to prevent duplicate instances
// across plugins whose node_modules live in sibling directories
dedupe: [...SHARED_DEPS, '@vue/runtime-core', '@vue/reactivity', '@vue/shared'],
alias: {
'@': path.resolve(import.meta.dirname, 'src'),
}
},
server: {
fs: {
@@ -37,12 +40,12 @@ export default defineConfig({
},
build: {
manifest: true,
outDir: path.resolve(__dirname, 'src/pretix/static.dist/vite/control'),
outDir: path.resolve(import.meta.dirname, 'src/pretix/static.dist/vite/control'),
rollupOptions: {
preserveEntrySignatures: 'exports-only',
input: {
'webcheckin/main': path.resolve(__dirname, 'src/pretix/plugins/webcheckin/static/pretixplugins/webcheckin/main.ts'),
'checkinrules/main': path.resolve(__dirname, 'src/pretix/static/pretixcontrol/js/ui/checkinrules/index.ts'),
'webcheckin/main': path.resolve(import.meta.dirname, 'src/pretix/plugins/webcheckin/static/pretixplugins/webcheckin/main.ts'),
'checkinrules/main': path.resolve(import.meta.dirname, 'src/pretix/static/pretixcontrol/js/ui/checkinrules/index.ts'),
...Object.fromEntries(SHARED_DEPS.map(dep => [`_vendor/${dep}`, `virtual:vendor/${dep}`])),
...pretixPluginEntries,
},