mirror of
https://github.com/pretix/pretix.git
synced 2026-11-26 03:51:56 +00:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e4b65ba49d | ||
|
|
071b8baf61 | ||
|
|
ff6922e2ce | ||
|
|
428d28e744 | ||
|
|
0de0ad6cae |
No files matched your search
@@ -123,7 +123,7 @@ jobs:
|
||||
working-directory: ./src
|
||||
run: make all compress
|
||||
- name: Install Playwright browsers
|
||||
run: playwright install chromium --with-deps
|
||||
run: playwright install --with-deps
|
||||
- name: Run E2E tests
|
||||
working-directory: ./src
|
||||
run: PRETIX_CONFIG_FILE=tests/ci_postgres.cfg py.test tests/e2e/ -v --maxfail=10 --tracing=retain-on-failure
|
||||
|
||||
@@ -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.
|
||||
|
||||
**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.
|
||||
**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.
|
||||
|
||||
.. note::
|
||||
|
||||
Do not use this API to redeem tickets if you're building a ticket scanning application, as it has a few design
|
||||
We no longer recommend using this API 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. (**Deprecated**, use the new :ref:`check-in API <rest-checkin>` instead)
|
||||
data to avoid guessing of ticket IDs.
|
||||
:>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
|
||||
|
||||
@@ -1,195 +0,0 @@
|
||||
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.
|
||||
|
||||
@@ -57,7 +57,6 @@ seating_plan integer If reserved sea
|
||||
seat_category_mapping object An object mapping categories of the seating plan
|
||||
(strings) to items in the event (integers or ``null``).
|
||||
last_modified datetime Last modification of this object
|
||||
comment string Internal comment for this subevent (or ``null``)
|
||||
===================================== ========================== =======================================================
|
||||
|
||||
.. versionchanged:: 2023.8.0
|
||||
@@ -118,10 +117,7 @@ Endpoints
|
||||
}
|
||||
],
|
||||
"variation_price_overrides": [],
|
||||
"meta_data": {},
|
||||
"frontpage_text": {},
|
||||
"last_modified": "2017-12-01T10:00:30Z",
|
||||
"comment": "internal comment"
|
||||
"meta_data": {}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -191,9 +187,7 @@ Endpoints
|
||||
}
|
||||
],
|
||||
"variation_price_overrides": [],
|
||||
"meta_data": {},
|
||||
"last_modified": "2017-12-01T10:00:30Z",
|
||||
"comment": ""
|
||||
"meta_data": {}
|
||||
}
|
||||
|
||||
|
||||
@@ -230,9 +224,7 @@ Endpoints
|
||||
}
|
||||
],
|
||||
"variation_price_overrides": [],
|
||||
"meta_data": {},
|
||||
"last_modified": "2017-12-01T10:00:30Z",
|
||||
"comment": ""
|
||||
"meta_data": {}
|
||||
}
|
||||
|
||||
|
||||
@@ -290,9 +282,7 @@ Endpoints
|
||||
}
|
||||
],
|
||||
"variation_price_overrides": [],
|
||||
"meta_data": {},
|
||||
"last_modified": "2017-12-01T10:00:30Z",
|
||||
"comment": ""
|
||||
"meta_data": {}
|
||||
}
|
||||
|
||||
:param organizer: The ``slug`` field of a valid organizer
|
||||
@@ -453,9 +443,7 @@ Endpoints
|
||||
}
|
||||
],
|
||||
"variation_price_overrides": [],
|
||||
"meta_data": {},
|
||||
"last_modified": "2017-12-01T10:00:30Z",
|
||||
"comment": ""
|
||||
"meta_data": {}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -43,6 +43,8 @@ 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',
|
||||
|
||||
+4
-6
@@ -34,7 +34,7 @@ dependencies = [
|
||||
"celery==5.6.*",
|
||||
"chardet==5.2.*",
|
||||
"cryptography>=50.0.2",
|
||||
"css-inline==0.24.*",
|
||||
"css-inline==0.23.*",
|
||||
"defusedcsv>=3.0.0",
|
||||
"dnspython==2.9.*",
|
||||
"Django[argon2]==5.2.*,>=5.2.17",
|
||||
@@ -62,7 +62,7 @@ dependencies = [
|
||||
"geoip2==5.*",
|
||||
"isoweek",
|
||||
"jsonschema",
|
||||
"kombu==5.7.*",
|
||||
"kombu==5.6.*",
|
||||
"libsass==0.23.*",
|
||||
"lxml",
|
||||
"markdown==3.11.2",
|
||||
@@ -80,7 +80,6 @@ dependencies = [
|
||||
"psycopg2-binary",
|
||||
"pycountry",
|
||||
"pycparser==3.12",
|
||||
"pycryptodome==3.24.*",
|
||||
"pypdf==6.21.*",
|
||||
"python-bidi==0.6.*", # Support for Arabic in reportlab
|
||||
"python-dateutil==4.0.*",
|
||||
@@ -91,7 +90,7 @@ dependencies = [
|
||||
"redis==7.4.*",
|
||||
"reportlab==5.1.*",
|
||||
"requests==2.34.*",
|
||||
"sentry-sdk==2.75.*",
|
||||
"sentry-sdk==2.71.*",
|
||||
"sepaxml==2.7.*",
|
||||
"stripe==7.9.*",
|
||||
"text-unidecode==1.*",
|
||||
@@ -123,8 +122,7 @@ dev = [
|
||||
"pytest-sugar",
|
||||
"pytest-xdist==3.8.*",
|
||||
"pytest-playwright",
|
||||
"pytest-base-url",
|
||||
"pytest==9.2.*",
|
||||
"pytest==9.1.*",
|
||||
"playwright",
|
||||
"responses",
|
||||
"pypdfium2"
|
||||
|
||||
@@ -155,6 +155,7 @@ class PretixScanNoSyncNoSearchSecurityProfile(AllowListSecurityProfile):
|
||||
('POST', 'api-v1:upload'),
|
||||
('POST', 'api-v1:checkinrpc.redeem'),
|
||||
('POST', 'api-v1:checkinrpc.annul'),
|
||||
('GET', 'api-v1:checkinrpc.search'),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -378,7 +378,6 @@ class ItemSerializer(SalesChannelMigrationMixin, I18nAwareModelSerializer):
|
||||
def validate_bundles(self, value):
|
||||
if not self.instance:
|
||||
for b_data in value:
|
||||
ItemBundle.clean_count(b_data.get('count', 1))
|
||||
ItemBundle.clean_itemvar(self.context['event'], b_data.get('bundled_item'), b_data.get('bundled_variation'))
|
||||
return value
|
||||
|
||||
@@ -387,8 +386,8 @@ class ItemSerializer(SalesChannelMigrationMixin, I18nAwareModelSerializer):
|
||||
for addon_data in value:
|
||||
ItemAddOn.clean_categories(self.context['event'], None, self.instance, addon_data['addon_category'])
|
||||
ItemAddOn.clean_min_count(addon_data.get('min_count', 0))
|
||||
ItemAddOn.clean_max_count(addon_data.get('max_count', 1))
|
||||
ItemAddOn.clean_max_min_count(addon_data.get('max_count', 1), addon_data.get('min_count', 0))
|
||||
ItemAddOn.clean_max_count(addon_data.get('max_count', 0))
|
||||
ItemAddOn.clean_max_min_count(addon_data.get('max_count', 0), addon_data.get('min_count', 0))
|
||||
return value
|
||||
|
||||
def validate_program_times(self, value):
|
||||
|
||||
@@ -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, Gate, GiftCard, GiftCardTransaction,
|
||||
Customer, Device, EventMetaProperty, GiftCard, GiftCardTransaction,
|
||||
Membership, MembershipType, OrderPosition, Organizer, ReusableMedium,
|
||||
SalesChannel, SeatingPlan, Team, TeamAPIToken, TeamInvite, User,
|
||||
)
|
||||
@@ -477,13 +477,6 @@ 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
|
||||
|
||||
@@ -62,7 +62,6 @@ 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)
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
#
|
||||
from datetime import timedelta
|
||||
|
||||
from celery.result import AsyncResult
|
||||
from django.conf import settings
|
||||
from django.db import transaction
|
||||
from django.http import Http404
|
||||
@@ -48,7 +49,6 @@ from pretix.base.services.export import (
|
||||
ExportError, export, init_event_exporters, init_organizer_exporters,
|
||||
multiexport,
|
||||
)
|
||||
from pretix.helpers.celery import get_task_result
|
||||
from pretix.helpers.http import ChunkBasedFileResponse
|
||||
|
||||
|
||||
@@ -91,7 +91,7 @@ class ExportersMixin:
|
||||
status=status.HTTP_410_GONE
|
||||
)
|
||||
|
||||
res = get_task_result(kwargs['asyncid'], task_name=self.task)
|
||||
res = AsyncResult(kwargs['asyncid'])
|
||||
if res.failed():
|
||||
if isinstance(res.info, dict) and res.info['exc_type'] == 'ExportError':
|
||||
msg = res.info['exc_message']
|
||||
@@ -139,7 +139,6 @@ class ExportersMixin:
|
||||
|
||||
class EventExportersViewSet(ExportersMixin, viewsets.ViewSet):
|
||||
permission = None
|
||||
task = export
|
||||
|
||||
@cached_property
|
||||
def exporters(self):
|
||||
@@ -174,7 +173,6 @@ class EventExportersViewSet(ExportersMixin, viewsets.ViewSet):
|
||||
|
||||
class OrganizerExportersViewSet(ExportersMixin, viewsets.ViewSet):
|
||||
permission = None
|
||||
task = multiexport
|
||||
|
||||
@cached_property
|
||||
def exporters(self):
|
||||
@@ -371,7 +369,6 @@ class ScheduledOrganizerExportViewSet(ScheduledExportersViewSet):
|
||||
elif self.request.user.is_authenticated:
|
||||
if not self.request.user.teams.filter(
|
||||
TeamQuerySet.event_permission_q(exporter.get_required_event_permission()),
|
||||
organizer=self.request.organizer,
|
||||
all_events=True,
|
||||
).exists():
|
||||
raise PermissionDenied("No permission to edit exports you could not run.")
|
||||
|
||||
@@ -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, GateSerializer, GiftCardSerializer,
|
||||
EventMetaPropertiesSerializer, GiftCardSerializer,
|
||||
GiftCardTransactionSerializer, MembershipSerializer,
|
||||
MembershipTypeSerializer, OrganizerSerializer, OrganizerSettingsSerializer,
|
||||
SalesChannelSerializer, SeatingPlanSerializer, TeamAPITokenSerializer,
|
||||
TeamInviteSerializer, TeamMemberSerializer, TeamSerializer,
|
||||
)
|
||||
from pretix.base.models import (
|
||||
Customer, Device, Event, EventMetaProperty, Gate, GiftCard,
|
||||
GiftCardTransaction, LogEntry, Membership, MembershipType, Organizer,
|
||||
SalesChannel, SeatingPlan, Team, TeamAPIToken, TeamInvite, User,
|
||||
Customer, Device, Event, EventMetaProperty, 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,52 +571,6 @@ 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'
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
#
|
||||
from datetime import timedelta
|
||||
|
||||
from celery.result import AsyncResult
|
||||
from django.conf import settings
|
||||
from django.http import Http404
|
||||
from django.shortcuts import get_object_or_404
|
||||
@@ -39,7 +40,6 @@ from pretix.api.serializers.shredders import (
|
||||
from pretix.base.models import CachedFile
|
||||
from pretix.base.services.shredder import export, shred
|
||||
from pretix.base.shredder import shred_constraints
|
||||
from pretix.helpers.celery import get_task_result
|
||||
from pretix.helpers.http import ChunkBasedFileResponse
|
||||
|
||||
|
||||
@@ -87,7 +87,7 @@ class ShreddersMixin:
|
||||
status=status.HTTP_410_GONE
|
||||
)
|
||||
|
||||
res = get_task_result(kwargs['asyncid'], task_name=export)
|
||||
res = AsyncResult(kwargs['asyncid'])
|
||||
if res.failed():
|
||||
if isinstance(res.info, dict) and res.info['exc_type'] in ('ShredError', 'ExportError'):
|
||||
msg = res.info['exc_message']
|
||||
@@ -108,7 +108,7 @@ class ShreddersMixin:
|
||||
@action(detail=False, methods=['GET'], url_name='status', url_path='status/(?P<asyncid>[^/]+)/(?P<cfid>[^/]+)')
|
||||
def status(self, *args, **kwargs):
|
||||
if settings.HAS_CELERY:
|
||||
res = get_task_result(kwargs['asyncid'], task_name=shred)
|
||||
res = AsyncResult(kwargs['asyncid'])
|
||||
if res.failed():
|
||||
if isinstance(res.info, dict) and res.info['exc_type'] in ('ShredError', 'ExportError'):
|
||||
msg = res.info['exc_message']
|
||||
@@ -141,17 +141,12 @@ class ShreddersMixin:
|
||||
status=status.HTTP_410_GONE
|
||||
)
|
||||
|
||||
if settings.HAS_CELERY:
|
||||
return Response(
|
||||
{
|
||||
'status': 'running' if res.state in ('PROGRESS', 'STARTED', 'SUCCESS') else 'waiting',
|
||||
},
|
||||
status=status.HTTP_409_CONFLICT
|
||||
)
|
||||
else:
|
||||
# This can't happen for clients who follow the api spec. They would need have to constructed the url themselves
|
||||
# from a valid shredder cached file, e.g. by modifying the URL retured by `export`.
|
||||
raise Http404()
|
||||
return Response(
|
||||
{
|
||||
'status': 'running' if res.state in ('PROGRESS', 'STARTED', 'SUCCESS') else 'waiting',
|
||||
},
|
||||
status=status.HTTP_409_CONFLICT
|
||||
)
|
||||
|
||||
@action(detail=False, methods=['POST'], url_name='shred', url_path='shred/(?P<asyncid>[^/]+)/(?P<cfid>[^/]+)')
|
||||
def shred(self, *args, **kwargs):
|
||||
@@ -168,10 +163,11 @@ class ShreddersMixin:
|
||||
raise Http404()
|
||||
if cf.file:
|
||||
async_result = self.do_shred(cf)
|
||||
url_kwargs = self.kwargs | {
|
||||
url_kwargs = {
|
||||
'asyncid': str(async_result.id),
|
||||
'cfid': str(cf.id),
|
||||
}
|
||||
url_kwargs.update(self.kwargs)
|
||||
return Response({
|
||||
'status': reverse('api-v1:shredders-status', kwargs=url_kwargs, request=self.request),
|
||||
}, status=status.HTTP_202_ACCEPTED)
|
||||
@@ -181,7 +177,7 @@ class ShreddersMixin:
|
||||
status=status.HTTP_410_GONE
|
||||
)
|
||||
|
||||
res = get_task_result(kwargs['asyncid'], task_name=export)
|
||||
res = AsyncResult(kwargs['asyncid'])
|
||||
if res.failed():
|
||||
if isinstance(res.info, dict) and res.info['exc_type'] in ('ShredError', 'ExportError'):
|
||||
msg = res.info['exc_message']
|
||||
|
||||
@@ -173,13 +173,11 @@ class UploadedFileWidget(forms.ClearableFileInput):
|
||||
|
||||
@property
|
||||
def url(self):
|
||||
from pretix.base.templatetags.safelink import answer_url
|
||||
|
||||
token = get_token(self.request, self.answer)
|
||||
if self.request.resolver_match.namespace == 'control':
|
||||
return self.answer.backend_file_url + '?token=' + token
|
||||
else:
|
||||
return answer_url(self.request, self.answer)
|
||||
return self.answer.frontend_file_url + '?token=' + token
|
||||
|
||||
def get_context(self, name, value, attrs):
|
||||
# Browsers can't recognize that the server already has a file uploaded
|
||||
|
||||
@@ -24,6 +24,7 @@ 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
|
||||
@@ -244,3 +245,49 @@ 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
|
||||
@@ -93,7 +93,7 @@ class Gate(LoggedModel):
|
||||
if instance:
|
||||
qs = qs.exclude(pk=instance.pk)
|
||||
if qs.exists():
|
||||
raise ValidationError(_('This identifier is already used for a different gate.'))
|
||||
raise ValidationError(_('This identifier is already used for a different question.'))
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
if not self.identifier:
|
||||
|
||||
@@ -621,8 +621,7 @@ 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. Please note that the waitinglist is not '
|
||||
'available for products requiring a voucher.')
|
||||
'either directly or via a quota.')
|
||||
)
|
||||
require_approval = models.BooleanField(
|
||||
verbose_name=_('Buying this product requires approval'),
|
||||
@@ -1344,8 +1343,6 @@ class ItemVariation(models.Model):
|
||||
quotacounter[q] += b.count
|
||||
|
||||
for q, n in quotacounter.items():
|
||||
if n == 0:
|
||||
continue
|
||||
a = q.availability(count_waitinglist=count_waitinglist, _cache=_cache)
|
||||
if a[1] is None:
|
||||
continue
|
||||
@@ -1489,8 +1486,8 @@ class ItemAddOn(models.Model):
|
||||
|
||||
@staticmethod
|
||||
def clean_max_count(max_count):
|
||||
if max_count < 1:
|
||||
raise ValidationError(_('The maximum count needs to be greater than zero.'))
|
||||
if max_count < 0:
|
||||
raise ValidationError(_('The maximum count needs to be equal to or greater than zero.'))
|
||||
|
||||
@staticmethod
|
||||
def clean_max_min_count(max_count, min_count):
|
||||
@@ -1571,8 +1568,8 @@ class ItemBundle(models.Model):
|
||||
|
||||
@staticmethod
|
||||
def clean_count(count):
|
||||
if count < 1:
|
||||
raise ValidationError(_('The count needs to be greater than zero.'))
|
||||
if count < 0:
|
||||
raise ValidationError(_('The count needs to be equal to or greater than zero.'))
|
||||
|
||||
|
||||
class Question(LoggedModel):
|
||||
|
||||
@@ -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 LoggedModel
|
||||
from .base import LockModel, 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(LoggedModel):
|
||||
class Order(LockModel, 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
|
||||
@@ -1349,6 +1349,25 @@ class QuestionAnswer(models.Model):
|
||||
})
|
||||
return ""
|
||||
|
||||
@property
|
||||
def frontend_file_url(self):
|
||||
from pretix.multidomain.urlreverse import eventreverse
|
||||
|
||||
if self.file:
|
||||
if self.associated_order:
|
||||
url = eventreverse(self.associated_order.event, 'presale:event.order.download.answer', kwargs={
|
||||
'order': self.associated_order.code,
|
||||
'secret': self.associated_order.secret,
|
||||
'answer': self.pk,
|
||||
})
|
||||
else:
|
||||
url = eventreverse(self.event, 'presale:event.cart.download.answer', kwargs={
|
||||
'answer': self.pk,
|
||||
})
|
||||
|
||||
return url
|
||||
return ""
|
||||
|
||||
@property
|
||||
def is_image(self):
|
||||
return any(self.file.name.lower().endswith(e) for e in settings.FILE_UPLOAD_EXTENSIONS_QUESTION_IMAGE)
|
||||
|
||||
@@ -1320,7 +1320,6 @@ DEFAULTS = {
|
||||
'invoice_generate_only_business': {
|
||||
'default': 'False',
|
||||
'type': bool,
|
||||
'write_permission': 'event.settings.invoicing:write',
|
||||
'form_class': forms.BooleanField,
|
||||
'serializer_class': serializers.BooleanField,
|
||||
'form_kwargs': dict(
|
||||
|
||||
@@ -23,13 +23,17 @@ 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_simple_block_tag(register)
|
||||
def dialog(content, html_id, title, description, *args, **kwargs):
|
||||
format_kwargs = {
|
||||
"id": html_id,
|
||||
|
||||
@@ -340,14 +340,7 @@ class LinkifyAndCleanExtension(Extension):
|
||||
)
|
||||
|
||||
|
||||
class SnippetExtension(markdown.extensions.Extension):
|
||||
def extendMarkdown(self, md, *args, **kwargs):
|
||||
md.parser.blockprocessors.deregister('olist')
|
||||
md.parser.blockprocessors.deregister('ulist')
|
||||
md.parser.blockprocessors.deregister('quote')
|
||||
|
||||
|
||||
def _get_email_markdown(allowed_tags=None, allowed_attributes=ALLOWED_ATTRIBUTES, snippet=False, context=None):
|
||||
def markdown_compile_email(source, allowed_tags=None, allowed_attributes=ALLOWED_ATTRIBUTES, snippet=False, context=None):
|
||||
if allowed_tags is None:
|
||||
allowed_tags = ALLOWED_TAGS_SNIPPET if snippet else ALLOWED_TAGS
|
||||
|
||||
@@ -388,16 +381,20 @@ def _get_email_markdown(allowed_tags=None, allowed_attributes=ALLOWED_ATTRIBUTES
|
||||
]
|
||||
if snippet:
|
||||
exts.append(SnippetExtension())
|
||||
|
||||
return markdown.Markdown(extensions=exts)
|
||||
return markdown.markdown(
|
||||
source,
|
||||
extensions=exts
|
||||
)
|
||||
|
||||
|
||||
def markdown_compile_email(source, allowed_tags=None, allowed_attributes=ALLOWED_ATTRIBUTES, snippet=False, context=None):
|
||||
md = _get_email_markdown(allowed_tags, allowed_attributes, snippet, context)
|
||||
return md.convert(source)
|
||||
class SnippetExtension(markdown.extensions.Extension):
|
||||
def extendMarkdown(self, md, *args, **kwargs):
|
||||
md.parser.blockprocessors.deregister('olist')
|
||||
md.parser.blockprocessors.deregister('ulist')
|
||||
md.parser.blockprocessors.deregister('quote')
|
||||
|
||||
|
||||
def _get_markdown(linker, snippet=False):
|
||||
def markdown_compile(source, linker, snippet=False):
|
||||
tags = ALLOWED_TAGS_SNIPPET if snippet else ALLOWED_TAGS
|
||||
exts = [
|
||||
'markdown.extensions.sane_lists',
|
||||
@@ -412,13 +409,10 @@ def _get_markdown(linker, snippet=False):
|
||||
]
|
||||
if snippet:
|
||||
exts.append(SnippetExtension())
|
||||
|
||||
return markdown.Markdown(extensions=exts)
|
||||
|
||||
|
||||
def markdown_compile(source, linker, snippet=False):
|
||||
md = _get_markdown(linker, snippet)
|
||||
return md.convert(source)
|
||||
return markdown.markdown(
|
||||
source,
|
||||
extensions=exts
|
||||
)
|
||||
|
||||
|
||||
@register.filter
|
||||
@@ -451,25 +445,3 @@ def rich_text_snippet(text: str, **kwargs):
|
||||
)
|
||||
body_md = markdown_compile(text, linker, snippet=True)
|
||||
return mark_safe(body_md)
|
||||
|
||||
|
||||
def _md_escape(md: markdown.Markdown, plain: str):
|
||||
escaped_chars = md.ESCAPED_CHARS
|
||||
translation_map = {ord(x): f"\\{x}" for x in escaped_chars}
|
||||
return plain.translate(translation_map)
|
||||
|
||||
|
||||
def markdown_escape(plain: str) -> str:
|
||||
"""
|
||||
Escape formatting characters in markdown with backslash using the default markdown renderer config.
|
||||
"""
|
||||
md = _get_markdown(bleach.Linker())
|
||||
return _md_escape(md, plain)
|
||||
|
||||
|
||||
def markdown_email_escape(plain: str) -> str:
|
||||
"""
|
||||
Escape formatting characters in markdown with backslash using the default email markdown renderer config.
|
||||
"""
|
||||
md = _get_email_markdown(None, False)
|
||||
return _md_escape(md, plain)
|
||||
@@ -22,7 +22,6 @@
|
||||
from django import template
|
||||
|
||||
from pretix.helpers.safedownload import get_token
|
||||
from pretix.multidomain.urlreverse import eventreverse
|
||||
|
||||
from ..views.redirect import safelink as sl
|
||||
|
||||
@@ -37,19 +36,3 @@ def safelink(url):
|
||||
@register.simple_tag
|
||||
def answer_token(request, answer):
|
||||
return get_token(request, answer)
|
||||
|
||||
|
||||
@register.simple_tag
|
||||
def answer_url(request, answer):
|
||||
if answer.file:
|
||||
if answer.associated_order:
|
||||
url = eventreverse(answer.associated_order.event, 'presale:event.download.answer', kwargs={
|
||||
'answer': answer.pk,
|
||||
})
|
||||
else:
|
||||
url = eventreverse(request.event, 'presale:event.cart.download.answer', kwargs={
|
||||
'answer': answer.pk,
|
||||
})
|
||||
|
||||
return url + "?token=" + get_token(request, answer)
|
||||
return ""
|
||||
@@ -28,6 +28,7 @@ from zoneinfo import ZoneInfo
|
||||
|
||||
import celery.exceptions
|
||||
from celery import states
|
||||
from celery.result import AsyncResult
|
||||
from django.conf import settings
|
||||
from django.contrib import messages
|
||||
from django.core.exceptions import (
|
||||
@@ -40,7 +41,6 @@ from django.shortcuts import render
|
||||
from django.test import RequestFactory
|
||||
from django.utils import timezone, translation
|
||||
from django.utils.datastructures import MultiValueDict
|
||||
from django.utils.functional import classproperty
|
||||
from django.utils.timezone import get_current_timezone, now
|
||||
from django.utils.translation import get_language, gettext as _
|
||||
from django.views import View
|
||||
@@ -50,7 +50,6 @@ from redis import ResponseError
|
||||
from pretix.base.models import CachedFile, User
|
||||
from pretix.base.services.tasks import ProfiledEventTask
|
||||
from pretix.celery_app import app
|
||||
from pretix.helpers.celery import get_task_result
|
||||
from pretix.helpers.http import redirect_to_url
|
||||
|
||||
logger = logging.getLogger('pretix.base.tasks')
|
||||
@@ -62,10 +61,6 @@ class AsyncMixin:
|
||||
error_url = None
|
||||
known_errortypes = []
|
||||
|
||||
@classproperty
|
||||
def task(self):
|
||||
raise NotImplementedError("Needs to be supplied by child class")
|
||||
|
||||
def get_success_url(self, value):
|
||||
return self.success_url
|
||||
|
||||
@@ -142,8 +137,7 @@ class AsyncMixin:
|
||||
raise BadRequest("No async_id given")
|
||||
if not RE_ASYNC_ID.match(request.GET.get('async_id')):
|
||||
raise BadRequest("Invalid async_id given")
|
||||
|
||||
res = get_task_result(request.GET.get('async_id'), task_name=self.task)
|
||||
res = AsyncResult(request.GET.get('async_id'))
|
||||
if 'ajax' in self.request.GET:
|
||||
return JsonResponse(self._return_ajax_result(res, timeout=0.25))
|
||||
else:
|
||||
@@ -323,10 +317,6 @@ class AsyncFormView(AsyncMixin, FormView):
|
||||
throws=cls.expected_exceptions
|
||||
)(async_execute)
|
||||
|
||||
@classproperty
|
||||
def task(cls): # noqa
|
||||
return cls.async_execute
|
||||
|
||||
def async_form_valid(self, task, form):
|
||||
pass
|
||||
|
||||
@@ -460,10 +450,6 @@ class AsyncPostView(AsyncMixin, View):
|
||||
def async_post(self, request, *args, **kwargs):
|
||||
pass
|
||||
|
||||
@classproperty
|
||||
def task(cls): # noqa
|
||||
return cls.async_execute
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
if 'async_id' in request.GET and settings.HAS_CELERY:
|
||||
return self.get_result(request)
|
||||
|
||||
@@ -1207,11 +1207,6 @@ class ItemAddOnForm(I18nModelForm):
|
||||
}
|
||||
)
|
||||
self.fields['addon_category'].widget.choices = self.fields['addon_category'].choices
|
||||
self.fields['max_count'] = forms.IntegerField(
|
||||
min_value=1,
|
||||
label=self.fields['max_count'].label,
|
||||
widget=forms.NumberInput(attrs={'placeholder': '1'}),
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = ItemAddOn
|
||||
@@ -1324,12 +1319,6 @@ class ItemBundleForm(I18nModelForm):
|
||||
self.fields['itemvar'].choices = choices
|
||||
change_decimal_field(self.fields['designated_price'], self.event.currency)
|
||||
|
||||
self.fields['count'] = forms.IntegerField(
|
||||
min_value=1,
|
||||
label=self.fields['count'].label,
|
||||
widget=forms.NumberInput(attrs={'placeholder': '1'}),
|
||||
)
|
||||
|
||||
def clean(self):
|
||||
d = super().clean()
|
||||
if not self.cleaned_data.get('designated_price'):
|
||||
|
||||
@@ -79,8 +79,8 @@ class WaitingListEntryEditForm(I18nModelForm):
|
||||
self.fields['name_parts'] = NamePartsFormField(
|
||||
max_length=255,
|
||||
required=self.event.settings.waiting_list_names_required,
|
||||
scheme=self.event.settings.name_scheme,
|
||||
titles=self.event.settings.name_scheme_titles,
|
||||
scheme=self.event.organizer.settings.name_scheme,
|
||||
titles=self.event.organizer.settings.name_scheme_titles,
|
||||
label=_('Name'),
|
||||
)
|
||||
else:
|
||||
|
||||
@@ -578,11 +578,13 @@
|
||||
class="btn btn-xs btn-default">
|
||||
<span class="fa fa-qrcode"></span> {% trans "Ticket code" %}
|
||||
</button>
|
||||
<a href="{% eventurl request.event "presale:event.order.position" order=order.code secret=line.web_secret position=line.positionid %}"
|
||||
class="btn btn-xs btn-default" target="_blank">
|
||||
<span class="fa fa-eye"></span>
|
||||
{% trans "Ticket page" %}
|
||||
</a>
|
||||
{% if not line.addon_to %}
|
||||
<a href="{% eventurl request.event "presale:event.order.position" order=order.code secret=line.web_secret position=line.positionid %}"
|
||||
class="btn btn-xs btn-default" target="_blank">
|
||||
<span class="fa fa-eye"></span>
|
||||
{% trans "Ticket page" %}
|
||||
</a>
|
||||
{% endif %}
|
||||
{% eventsignal event "pretix.control.signals.order_position_buttons" order=order position=line request=request %}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
@@ -39,16 +39,6 @@
|
||||
</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,26 +242,20 @@
|
||||
<p> </p>
|
||||
<fieldset>
|
||||
<legend>{% trans "Check-in lists" %}</legend>
|
||||
{% if block_list_change %}
|
||||
{% if sampled_lists|default_if_none:"NONE" == "NONE" %}
|
||||
<div class="alert alert-info">
|
||||
{% blocktrans trimmed %}
|
||||
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.
|
||||
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.
|
||||
{% 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">
|
||||
{% 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="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="formset" data-formset data-formset-prefix="{{ cl_formset.prefix }}">
|
||||
{{ cl_formset.management_form }}
|
||||
{% bootstrap_formset_errors cl_formset %}
|
||||
|
||||
@@ -130,7 +130,6 @@ class OutgoingMailDetailView(OrganizerDetailViewMixin, OrganizerPermissionRequir
|
||||
|
||||
|
||||
class OutgoingMailBulkAction(OutgoingMailQueryMixin, OrganizerPermissionRequiredMixin, OrganizerDetailViewMixin, View):
|
||||
# Yes, read permission here includes retry and cancelling emails, this is intentional and documented
|
||||
permission = 'organizer.outgoingmails:read'
|
||||
|
||||
@transaction.atomic
|
||||
|
||||
@@ -43,6 +43,7 @@ from datetime import datetime, time, timedelta
|
||||
from decimal import Decimal, DecimalException
|
||||
from urllib.parse import quote, urlencode
|
||||
|
||||
from celery.result import AsyncResult
|
||||
from django import forms
|
||||
from django.conf import settings
|
||||
from django.contrib import messages
|
||||
@@ -135,7 +136,6 @@ from pretix.control.permissions import (
|
||||
from pretix.control.signals import order_search_forms
|
||||
from pretix.control.views import PaginationMixin
|
||||
from pretix.helpers import OF_SELF
|
||||
from pretix.helpers.celery import get_task_result
|
||||
from pretix.helpers.compat import CompatDeleteView
|
||||
from pretix.helpers.format import SafeFormatter, format_map
|
||||
from pretix.helpers.hierarkey import clean_filename
|
||||
@@ -2772,11 +2772,7 @@ class ExportMixin:
|
||||
@cached_property
|
||||
def scheduled_copy_from(self):
|
||||
if "scheduled_copy_from" in self.request.GET:
|
||||
return get_object_or_404(
|
||||
self.get_scheduled_queryset(),
|
||||
pk=self.request.GET.get("scheduled_copy_from"),
|
||||
export_identifier=self.request.GET.get("identifier") or self.request.POST.get("exporter") or self.request.GET.get("exporter"),
|
||||
)
|
||||
return get_object_or_404(self.get_scheduled_queryset(), pk=self.request.GET.get("scheduled_copy_from"))
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
ctx = super().get_context_data(**kwargs)
|
||||
@@ -2928,10 +2924,6 @@ class ExportView(EventPermissionRequiredMixin, ExportMixin, ListView):
|
||||
if self.scheduled_copy_from:
|
||||
instance = copy.copy(self.scheduled_copy_from)
|
||||
instance.pk = None
|
||||
instance.owner = self.request.user
|
||||
instance.schedule_next_run = None
|
||||
instance.error_counter = 0
|
||||
instance.last_error = None
|
||||
else:
|
||||
instance = self.scheduled or ScheduledEventExport(
|
||||
event=self.request.event,
|
||||
@@ -3169,14 +3161,14 @@ class EventCancel(EventPermissionRequiredMixin, AsyncAction, FormView):
|
||||
|
||||
class EventCancelConfirm(EventPermissionRequiredMixin, AsyncAction, FormView):
|
||||
template_name = 'pretixcontrol/orders/cancel_confirm.html'
|
||||
permission = 'event:cancel'
|
||||
permission = 'event.orders:write'
|
||||
form_class = EventCancelConfirmForm
|
||||
task = cancel_event
|
||||
known_errortypes = ['OrderError']
|
||||
|
||||
@cached_property
|
||||
def dryrun_result(self):
|
||||
res = get_task_result(self.kwargs.get("task"), task_name=self.task)
|
||||
res = AsyncResult(self.kwargs.get("task"))
|
||||
if not res.ready():
|
||||
raise Http404()
|
||||
if not res.successful():
|
||||
|
||||
@@ -2056,11 +2056,7 @@ class ExportMixin:
|
||||
@cached_property
|
||||
def scheduled_copy_from(self):
|
||||
if "scheduled_copy_from" in self.request.GET:
|
||||
return get_object_or_404(
|
||||
self.get_scheduled_queryset(),
|
||||
pk=self.request.GET.get("scheduled_copy_from"),
|
||||
export_identifier=self.request.GET.get("identifier") or self.request.POST.get("exporter") or self.request.GET.get("exporter"),
|
||||
)
|
||||
return get_object_or_404(self.get_scheduled_queryset(), pk=self.request.GET.get("scheduled_copy_from"))
|
||||
|
||||
|
||||
class ExportDoView(OrganizerPermissionRequiredMixin, ExportMixin, AsyncAction, TemplateView):
|
||||
@@ -2210,10 +2206,6 @@ class ExportView(OrganizerPermissionRequiredMixin, ExportMixin, ListView):
|
||||
if self.scheduled_copy_from:
|
||||
instance = copy.copy(self.scheduled_copy_from)
|
||||
instance.pk = None
|
||||
instance.owner = self.request.user
|
||||
instance.schedule_next_run = None
|
||||
instance.error_counter = 0
|
||||
instance.last_error = None
|
||||
else:
|
||||
instance = self.scheduled or ScheduledOrganizerExport(
|
||||
organizer=self.request.organizer,
|
||||
@@ -2271,7 +2263,6 @@ class ExportView(OrganizerPermissionRequiredMixin, ExportMixin, ListView):
|
||||
# Test scenario 1/2 in test_organizer_edit_restrictions
|
||||
return self.request.user.teams.filter(
|
||||
TeamQuerySet.event_permission_q(self.exporter.get_required_event_permission()),
|
||||
organizer=self.request.organizer,
|
||||
all_events=True,
|
||||
).exists()
|
||||
else:
|
||||
|
||||
@@ -60,7 +60,7 @@ from django.views.generic import (
|
||||
)
|
||||
|
||||
from pretix.base.models import CartPosition, LogEntry, OrderPosition
|
||||
from pretix.base.models.checkin import Checkin, CheckinList
|
||||
from pretix.base.models.checkin import CheckinList
|
||||
from pretix.base.models.event import SubEvent, SubEventMetaValue
|
||||
from pretix.base.models.items import (
|
||||
Item, ItemVariation, Quota, SubEventItem, SubEventItemVariation,
|
||||
@@ -1320,13 +1320,9 @@ class SubEventBulkEdit(SubEventQueryMixin, EventPermissionRequiredMixin, FormVie
|
||||
extra = 0
|
||||
kwargs = {}
|
||||
|
||||
if self.block_list_change:
|
||||
if self.sampled_lists is None:
|
||||
return None
|
||||
if self.sampled_lists is not None:
|
||||
try:
|
||||
kwargs['instance'] = self.get_queryset()[0]
|
||||
except IndexError:
|
||||
raise Http404("No matching dates")
|
||||
kwargs['instance'] = self.get_queryset()[0]
|
||||
|
||||
formsetclass = inlineformset_factory(
|
||||
SubEvent, CheckinList,
|
||||
@@ -1339,7 +1335,7 @@ class SubEventBulkEdit(SubEventQueryMixin, EventPermissionRequiredMixin, FormVie
|
||||
)
|
||||
|
||||
def save_list_formset(self, log_entries):
|
||||
if self.block_list_change or not self.list_formset.has_changed():
|
||||
if self.sampled_lists is None or not self.list_formset.has_changed():
|
||||
return
|
||||
qidx = 0
|
||||
subevents = list(self.get_queryset().prefetch_related('checkinlist_set'))
|
||||
@@ -1347,21 +1343,6 @@ 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
|
||||
@@ -1513,7 +1494,6 @@ 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,7 +1520,6 @@ class SubEventBulkEdit(SubEventQueryMixin, EventPermissionRequiredMixin, FormVie
|
||||
|
||||
quotas_by_subevent = defaultdict(set)
|
||||
for q in all_quotas:
|
||||
# Normalize lists returned from PostgreSQL
|
||||
if q['item_list']:
|
||||
q['item_list'] = ",".join(sorted(q['item_list'].split(',')))
|
||||
if q['var_list']:
|
||||
@@ -1560,14 +1539,6 @@ 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(
|
||||
@@ -1587,11 +1558,6 @@ class SubEventBulkEdit(SubEventQueryMixin, EventPermissionRequiredMixin, FormVie
|
||||
|
||||
lists_by_subevent = defaultdict(list)
|
||||
for cl in all_lists:
|
||||
# Normalize lists returned from PostgreSQL
|
||||
if cl['item_list']:
|
||||
cl['item_list'] = ",".join(sorted(cl['item_list'].split(',')))
|
||||
if cl['gates_list']:
|
||||
cl['gates_list'] = ",".join(sorted(cl['gates_list'].split(',')))
|
||||
lists_by_subevent[cl.pop('subevent')].append(cl)
|
||||
|
||||
prev = None
|
||||
|
||||
@@ -19,12 +19,7 @@
|
||||
# You should have received a copy of the GNU Affero General Public License along with this program. If not, see
|
||||
# <https://www.gnu.org/licenses/>.
|
||||
#
|
||||
from typing import Union
|
||||
|
||||
from celery import Task
|
||||
from celery.result import AsyncResult
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import SuspiciousOperation
|
||||
|
||||
THRESHOLD_DOWNGRADE_TO_MID = 50
|
||||
THRESHOLD_DOWNGRADE_TO_LOW = 250
|
||||
@@ -65,27 +60,3 @@ def get_task_priority(shard, organizer_id):
|
||||
return settings.PRIORITY_CELERY_MID
|
||||
else:
|
||||
return settings.PRIORITY_CELERY_HIGH
|
||||
|
||||
|
||||
class SafeAsyncResult(AsyncResult):
|
||||
def __init__(self, *args, expected_task_name, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.__expected_task_name = expected_task_name
|
||||
|
||||
def _maybe_set_cache(self, meta):
|
||||
if meta and meta['status'] != "PENDING":
|
||||
if meta.get('name') != self.__expected_task_name:
|
||||
raise SuspiciousOperation(
|
||||
f"Received task result for {meta.get('name')!r}, but expected '{self.__expected_task_name}'"
|
||||
)
|
||||
return super()._maybe_set_cache(meta)
|
||||
|
||||
|
||||
def get_task_result(task_id: str, task_name: Union[Task, str]) -> SafeAsyncResult:
|
||||
"""
|
||||
Returns an AsyncResult by it's ID in a safe way, i.e. do not return anything if the task
|
||||
name does not match the expected task.
|
||||
"""
|
||||
if isinstance(task_name, Task):
|
||||
task_name = task_name.name
|
||||
return SafeAsyncResult(task_id, expected_task_name=task_name)
|
||||
@@ -25,7 +25,6 @@ import types
|
||||
from datetime import datetime
|
||||
from http import cookies
|
||||
|
||||
from celery.backends.base import Backend
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import SuspiciousFileOperation
|
||||
from django.middleware.csrf import CsrfViewMiddleware as BaseCsrfMiddleware
|
||||
@@ -259,26 +258,6 @@ def monkeypatch_json_constants():
|
||||
del _CONSTANTS['NaN']
|
||||
|
||||
|
||||
def monkeypatch_celery_result_meta():
|
||||
"""
|
||||
We basically want `result_extended` from Celery to tie results to the tasks that created them,
|
||||
but just enabling `result_extended` will include full `args` and `kwargs` to the result which
|
||||
might contain large or sensitive data and we currently have no interest in storing them in the
|
||||
task backend without necessity.
|
||||
"""
|
||||
old__get_result_meta = Backend._get_result_meta
|
||||
|
||||
def new__get_result_meta(self, result, state, traceback, request, *args, **kwargs):
|
||||
meta = types.MethodType(old__get_result_meta, self)(
|
||||
result, state, traceback, request, *args, **kwargs,
|
||||
)
|
||||
if request and 'name' not in meta:
|
||||
meta['name'] = getattr(request, 'task', None)
|
||||
return meta
|
||||
|
||||
Backend._get_result_meta = new__get_result_meta
|
||||
|
||||
|
||||
def monkeypatch_all_at_ready():
|
||||
monkeypatch_vobject_performance()
|
||||
monkeypatch_pillow_safer()
|
||||
@@ -288,4 +267,3 @@ def monkeypatch_all_at_ready():
|
||||
monkeypatch_reportlab_imagereader()
|
||||
monkeypatch_csrf_middleware()
|
||||
monkeypatch_json_constants()
|
||||
monkeypatch_celery_result_meta()
|
||||
@@ -31,13 +31,13 @@ class SafeDownloadSigner(TimestampSigner):
|
||||
def get_token(request, answer):
|
||||
if not request.session.session_key:
|
||||
request.session.create()
|
||||
payload = '{}:{}:{}'.format(request.session.session_key, answer.pk, answer.file.name)
|
||||
payload = '{}:{}'.format(request.session.session_key, answer.pk)
|
||||
signer = SafeDownloadSigner()
|
||||
return signer.sign(hashlib.sha1(payload.encode()).hexdigest())
|
||||
|
||||
|
||||
def check_token(request, answer, token):
|
||||
payload = hashlib.sha1('{}:{}:{}'.format(request.session.session_key, answer.pk, answer.file.name).encode()).hexdigest()
|
||||
payload = hashlib.sha1('{}:{}'.format(request.session.session_key, answer.pk).encode()).hexdigest()
|
||||
signer = SafeDownloadSigner()
|
||||
try:
|
||||
return payload == signer.unsign(token, max_age=3600 * 24)
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
#
|
||||
# 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")
|
||||
@@ -8,8 +8,8 @@ msgstr ""
|
||||
"Project-Id-Version: PACKAGE VERSION\n"
|
||||
"Report-Msgid-Bugs-To: \n"
|
||||
"POT-Creation-Date: 2026-10-28 10:48+0000\n"
|
||||
"PO-Revision-Date: 2026-11-19 18:00+0000\n"
|
||||
"Last-Translator: Tim <plicnetwork@gmail.com>\n"
|
||||
"PO-Revision-Date: 2026-10-29 17:00+0000\n"
|
||||
"Last-Translator: CVZ-es <damien.bremont@casadevelazquez.org>\n"
|
||||
"Language-Team: Spanish <https://translate.pretix.eu/projects/pretix/pretix/"
|
||||
"es/>\n"
|
||||
"Language: es\n"
|
||||
@@ -17,7 +17,7 @@ msgstr ""
|
||||
"Content-Type: text/plain; charset=UTF-8\n"
|
||||
"Content-Transfer-Encoding: 8bit\n"
|
||||
"Plural-Forms: nplurals=2; plural=n != 1;\n"
|
||||
"X-Generator: Weblate 2026.11.2\n"
|
||||
"X-Generator: Weblate 2026.10.1\n"
|
||||
|
||||
#: pretix/_base_settings.py
|
||||
msgid "English"
|
||||
@@ -29522,7 +29522,7 @@ msgstr ""
|
||||
"Le hemos reembolsado {amount} por su pedido.\n"
|
||||
"\n"
|
||||
"Puede utilizar el código de la tarjeta regalo {giftcard} para pagar futuras "
|
||||
"reservas.\n"
|
||||
"compras en nuestra tienda.\n"
|
||||
"\n"
|
||||
"El equipo de {event}"
|
||||
|
||||
|
||||
@@ -51,7 +51,6 @@ from pretix.base.forms import I18nMarkdownTextarea
|
||||
from pretix.base.models import InvoiceAddress, Order, OrderPayment, OrderRefund
|
||||
from pretix.base.payment import BasePaymentProvider
|
||||
from pretix.base.templatetags.money import money_filter
|
||||
from pretix.base.templatetags.rich_text import markdown_email_escape
|
||||
from pretix.helpers.payment import generate_payment_qr_codes
|
||||
from pretix.plugins.banktransfer.templatetags.ibanformat import ibanformat
|
||||
from pretix.presale.views.cart import cart_session
|
||||
@@ -309,7 +308,7 @@ class BankTransfer(BasePaymentProvider):
|
||||
(_("Reference"), self._code(order, force=True)),
|
||||
(_("Amount"), money_filter(payment.amount, self.event.currency)),
|
||||
)
|
||||
t += md_nl2br.join([f"**{markdown_email_escape(k)}:** {markdown_email_escape(v)}" for k, v in bankdetails])
|
||||
t += md_nl2br.join([f"**{k}:** {v}" for k, v in bankdetails])
|
||||
if self.settings.get('bank_details', as_type=LazyI18nString):
|
||||
t += md_nl2br
|
||||
t += str(self.settings.get('bank_details', as_type=LazyI18nString))
|
||||
|
||||
@@ -1161,6 +1161,33 @@ 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
|
||||
|
||||
@@ -24,13 +24,14 @@ from django.urls import include, re_path
|
||||
from pretix.multidomain import event_url
|
||||
|
||||
from .views import (
|
||||
OrganizerSettingsFormView, ScaReturnView, ScaView, oauth_disconnect,
|
||||
oauth_return, webhook,
|
||||
OrganizerSettingsFormView, ReturnView, ScaReturnView, ScaView,
|
||||
oauth_disconnect, oauth_return, webhook,
|
||||
)
|
||||
|
||||
event_patterns = [
|
||||
re_path(r'^stripe/', include([
|
||||
event_url(r'^webhook/$', webhook, name='webhook', require_live=False),
|
||||
re_path(r'^return/(?P<order>[^/]+)/(?P<hash>[^/]+)/(?P<payment>[0-9]+)/$', ReturnView.as_view(), name='return'),
|
||||
re_path(r'^sca/(?P<order>[^/]+)/(?P<hash>[^/]+)/(?P<payment>[0-9]+)/$', ScaView.as_view(), name='sca'),
|
||||
re_path(r'^sca/(?P<order>[^/]+)/(?P<hash>[^/]+)/(?P<payment>[0-9]+)/return/$',
|
||||
ScaReturnView.as_view(), name='sca.return'),
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
#
|
||||
# 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/>.
|
||||
#
|
||||
@@ -175,51 +175,60 @@ def oauth_return(request, *args, **kwargs):
|
||||
@require_POST
|
||||
@scopes_disabled()
|
||||
def webhook(request, *args, **kwargs):
|
||||
untrusted_json = json.loads(request.body.decode('utf-8'))
|
||||
untrusted_obj = untrusted_json['data']['object']
|
||||
event_json = json.loads(request.body.decode('utf-8'))
|
||||
|
||||
# We do not check for the event type as we are not interested in the event it self,
|
||||
# we just use it as a trigger to look the charge up to be absolutely sure.
|
||||
# Another reason for this is that stripe events are not authenticated, so they could
|
||||
# come from anywhere.
|
||||
|
||||
rso_qs = ReferencedStripeObject.objects.select_related('order', 'order__event')
|
||||
|
||||
if untrusted_obj['object'] == "payment_intent":
|
||||
pi_id = untrusted_obj['id']
|
||||
try:
|
||||
rso = rso_qs.get(reference=pi_id)
|
||||
except ReferencedStripeObject.DoesNotExist:
|
||||
return HttpResponse("Unable to detect event", status=200)
|
||||
else:
|
||||
return paymentintent_webhook(untrusted_json, pi_id, rso)
|
||||
|
||||
elif untrusted_obj['object'] == "charge":
|
||||
charge_id = untrusted_obj['id']
|
||||
elif untrusted_obj['object'] == "dispute":
|
||||
charge_id = untrusted_obj['charge']
|
||||
if event_json['data']['object']['object'] == "charge":
|
||||
func = charge_webhook
|
||||
objid = event_json['data']['object']['id']
|
||||
lookup_ids = [
|
||||
objid,
|
||||
(event_json['data']['object'].get('source') or {}).get('id')
|
||||
]
|
||||
elif event_json['data']['object']['object'] == "dispute":
|
||||
func = charge_webhook
|
||||
objid = event_json['data']['object']['charge']
|
||||
lookup_ids = [objid]
|
||||
elif event_json['data']['object']['object'] == "source":
|
||||
func = source_webhook
|
||||
objid = event_json['data']['object']['id']
|
||||
lookup_ids = [objid]
|
||||
elif event_json['data']['object']['object'] == "payment_intent":
|
||||
func = paymentintent_webhook
|
||||
objid = event_json['data']['object']['id']
|
||||
lookup_ids = [objid]
|
||||
else:
|
||||
return HttpResponse("Not interested in this data type", status=200)
|
||||
|
||||
rso = None
|
||||
try:
|
||||
rso = rso_qs.get(reference=charge_id)
|
||||
except ReferencedStripeObject.DoesNotExist:
|
||||
if 'payment_intent' in untrusted_obj:
|
||||
# If we receive a charge webhook *before* the payment intent webhook, we don't know the charge ID yet
|
||||
# and can't match it -- but we know the payment intent ID! In charge_webhook, we validate that the
|
||||
# RSO's pi_id actually matches the pi_id returned by stripe API for the charge.
|
||||
try:
|
||||
rso = rso_qs.get(reference=untrusted_obj['payment_intent'])
|
||||
except ReferencedStripeObject.DoesNotExist:
|
||||
pass
|
||||
|
||||
rso = ReferencedStripeObject.objects.select_related('order', 'order__event').filter(
|
||||
reference__in=[lid for lid in lookup_ids if lid]
|
||||
).first()
|
||||
if rso:
|
||||
return charge_webhook(untrusted_json, charge_id, rso)
|
||||
return func(rso.order.event, event_json, objid, rso)
|
||||
else:
|
||||
# Okay, this is probably not an event that concerns us, maybe other applications talk to the same stripe
|
||||
# account
|
||||
return HttpResponse("Unable to detect event", status=200)
|
||||
if event_json['data']['object']['object'] == "charge" and 'payment_intent' in event_json['data']['object']:
|
||||
# If we receive a charge webhook *before* the payment intent webhook, we don't know the charge ID yet
|
||||
# and can't match it -- but we know the payment intent ID!
|
||||
try:
|
||||
rso = ReferencedStripeObject.objects.select_related('order', 'order__event').get(
|
||||
reference=event_json['data']['object']['payment_intent']
|
||||
)
|
||||
return func(rso.order.event, event_json, objid, rso)
|
||||
except ReferencedStripeObject.DoesNotExist:
|
||||
return HttpResponse("Unable to detect event", status=200)
|
||||
elif hasattr(request, 'event') and func != paymentintent_webhook:
|
||||
# This is a legacy integration from back when didn't have ReferencedStripeObject. This can't happen for
|
||||
# payment intents or charges connected with payment intents since they didn't exist back then. Our best
|
||||
# hope is to go for request.event and see if we can find the order ID.
|
||||
return func(request.event, event_json, objid, None)
|
||||
else:
|
||||
# Okay, this is probably not an event that concerns us, maybe other applications talk to the same stripe
|
||||
# account
|
||||
return HttpResponse("Unable to detect event", status=200)
|
||||
|
||||
|
||||
SOURCE_TYPES = {
|
||||
@@ -234,12 +243,12 @@ SOURCE_TYPES = {
|
||||
}
|
||||
|
||||
|
||||
def charge_webhook(untrusted_json, charge_id, rso):
|
||||
def charge_webhook(event, event_json, charge_id, rso):
|
||||
import stripe
|
||||
|
||||
from pretix.plugins.stripe.payment import StripeCC
|
||||
|
||||
prov = StripeCC(rso.order.event)
|
||||
prov = StripeCC(event)
|
||||
prov._init_api()
|
||||
|
||||
try:
|
||||
@@ -249,34 +258,51 @@ def charge_webhook(untrusted_json, charge_id, rso):
|
||||
**prov.api_kwargs
|
||||
)
|
||||
except stripe.error.StripeError:
|
||||
logger.exception('Stripe error on webhook. Event data: %s' % str(untrusted_json))
|
||||
logger.exception('Stripe error on webhook. Event data: %s' % str(event_json))
|
||||
return HttpResponse('Charge not found', status=500)
|
||||
|
||||
metadata = charge['metadata']
|
||||
if 'event' not in metadata:
|
||||
return HttpResponse('Event not given in charge metadata', status=200)
|
||||
|
||||
if int(metadata['event']) != rso.order.event.pk:
|
||||
if int(metadata['event']) != event.pk:
|
||||
return HttpResponse('Not interested in this event', status=200)
|
||||
|
||||
# Check the charge we fetched from stripe actually matches our RSO, and as such our own payment and order objects
|
||||
allowed_references = [charge.id]
|
||||
if getattr(charge, "payment_intent", None):
|
||||
allowed_references.append(charge.payment_intent.id)
|
||||
if rso.reference not in allowed_references:
|
||||
return HttpResponse('Charge mismatched', status=200)
|
||||
|
||||
order = rso.payment.order
|
||||
payment = rso.payment
|
||||
if rso and rso.payment:
|
||||
order = rso.payment.order
|
||||
payment = rso.payment
|
||||
elif rso:
|
||||
order = rso.order
|
||||
payment = None
|
||||
else:
|
||||
try:
|
||||
order = event.orders.get(id=metadata['order'])
|
||||
except Order.DoesNotExist:
|
||||
return HttpResponse('Order not found', status=200)
|
||||
payment = None
|
||||
|
||||
with transaction.atomic():
|
||||
payment = OrderPayment.objects.select_for_update(of=OF_SELF).get(pk=payment.pk)
|
||||
if payment:
|
||||
payment = OrderPayment.objects.select_for_update(of=OF_SELF).get(pk=payment.pk)
|
||||
else:
|
||||
payment = order.payments.filter(
|
||||
info__icontains=charge['id'],
|
||||
provider__startswith='stripe',
|
||||
amount=prov._amount_to_decimal(charge['amount']),
|
||||
).select_for_update(of=OF_SELF).last()
|
||||
if not payment:
|
||||
payment = order.payments.create(
|
||||
state=OrderPayment.PAYMENT_STATE_CREATED,
|
||||
provider=SOURCE_TYPES.get(charge['source'].get('type', charge['source'].get('object', 'card')), 'stripe'),
|
||||
amount=prov._amount_to_decimal(charge['amount']),
|
||||
info=str(charge),
|
||||
)
|
||||
|
||||
if payment.provider != prov.identifier:
|
||||
prov = payment.payment_provider
|
||||
prov._init_api()
|
||||
|
||||
order.log_action('pretix.plugins.stripe.event', data=untrusted_json)
|
||||
order.log_action('pretix.plugins.stripe.event', data=event_json)
|
||||
|
||||
is_refund = charge['amount_refunded'] or charge['refunds']['total_count'] or charge['dispute']
|
||||
if is_refund:
|
||||
@@ -324,18 +350,91 @@ def charge_webhook(untrusted_json, charge_id, rso):
|
||||
return HttpResponse(status=200)
|
||||
|
||||
|
||||
def paymentintent_webhook(untrusted_json, paymentintent_id, rso):
|
||||
def source_webhook(event, event_json, source_id, rso):
|
||||
import stripe
|
||||
|
||||
from pretix.plugins.stripe.payment import StripeCC
|
||||
|
||||
prov = StripeCC(rso.order.event)
|
||||
prov = StripeCC(event)
|
||||
prov._init_api()
|
||||
try:
|
||||
src = stripe.Source.retrieve(source_id, **prov.api_kwargs)
|
||||
except stripe.error.StripeError:
|
||||
logger.exception('Stripe error on webhook. Event data: %s' % str(event_json))
|
||||
return HttpResponse('Charge not found', status=500)
|
||||
|
||||
metadata = src['metadata']
|
||||
if 'event' not in metadata:
|
||||
return HttpResponse('Event not given in charge metadata', status=200)
|
||||
|
||||
if int(metadata['event']) != event.pk:
|
||||
return HttpResponse('Not interested in this event', status=200)
|
||||
|
||||
with transaction.atomic():
|
||||
if rso and rso.payment:
|
||||
order = rso.payment.order
|
||||
payment = rso.payment
|
||||
elif rso:
|
||||
order = rso.order
|
||||
payment = None
|
||||
else:
|
||||
try:
|
||||
order = event.orders.get(id=metadata['order'])
|
||||
except Order.DoesNotExist:
|
||||
return HttpResponse('Order not found', status=200)
|
||||
payment = None
|
||||
|
||||
if payment:
|
||||
payment = OrderPayment.objects.select_for_update(of=OF_SELF).get(pk=payment.pk)
|
||||
else:
|
||||
payment = order.payments.filter(
|
||||
info__icontains=src['id'],
|
||||
provider__startswith='stripe',
|
||||
amount=prov._amount_to_decimal(src['amount']) if src['amount'] is not None else order.total,
|
||||
).select_for_update(of=OF_SELF).last()
|
||||
if not payment:
|
||||
payment = order.payments.create(
|
||||
state=OrderPayment.PAYMENT_STATE_CREATED,
|
||||
provider=SOURCE_TYPES.get(src['type'], 'stripe'),
|
||||
amount=prov._amount_to_decimal(src['amount']) if src['amount'] is not None else order.total,
|
||||
info=str(src),
|
||||
)
|
||||
|
||||
if payment.provider != prov.identifier:
|
||||
prov = payment.payment_provider
|
||||
prov._init_api()
|
||||
|
||||
order.log_action('pretix.plugins.stripe.event', data=event_json)
|
||||
go = (event_json['type'] == 'source.chargeable' and
|
||||
payment.state in (OrderPayment.PAYMENT_STATE_PENDING, OrderPayment.PAYMENT_STATE_CREATED) and
|
||||
src.status == 'chargeable')
|
||||
if go:
|
||||
try:
|
||||
prov._charge_source(None, source_id, payment)
|
||||
except PaymentException:
|
||||
logger.exception('Webhook error')
|
||||
elif src.status == 'failed':
|
||||
payment.fail(info=str(src))
|
||||
elif src.status == 'canceled' and payment.state in (OrderPayment.PAYMENT_STATE_PENDING, OrderPayment.PAYMENT_STATE_CREATED):
|
||||
payment.info = str(src)
|
||||
payment.state = OrderPayment.PAYMENT_STATE_CANCELED
|
||||
payment.save()
|
||||
|
||||
return HttpResponse(status=200)
|
||||
|
||||
|
||||
def paymentintent_webhook(event, event_json, paymentintent_id, rso):
|
||||
import stripe
|
||||
|
||||
from pretix.plugins.stripe.payment import StripeCC
|
||||
|
||||
prov = StripeCC(event)
|
||||
prov._init_api()
|
||||
|
||||
try:
|
||||
paymentintent = stripe.PaymentIntent.retrieve(paymentintent_id, expand=["latest_charge"], **prov.api_kwargs)
|
||||
except stripe.error.StripeError:
|
||||
logger.exception('Stripe error on webhook. Event data: %s' % str(untrusted_json))
|
||||
logger.exception('Stripe error on webhook. Event data: %s' % str(event_json))
|
||||
return HttpResponse('Charge not found', status=500)
|
||||
|
||||
if paymentintent.latest_charge:
|
||||
@@ -344,15 +443,13 @@ def paymentintent_webhook(untrusted_json, paymentintent_id, rso):
|
||||
defaults={'order': rso.payment.order, 'payment': rso.payment}
|
||||
)
|
||||
|
||||
# We consider the risk acceptable that someone who knows the payment intent ID can
|
||||
# mark a pending payment as failed, therefore we 'trust' the event type here:
|
||||
if untrusted_json["type"] == "payment_intent.payment_failed":
|
||||
rso.payment.fail(info=str(paymentintent), log_data=untrusted_json)
|
||||
if event_json["type"] == "payment_intent.payment_failed":
|
||||
rso.payment.fail(info=event_json)
|
||||
|
||||
return HttpResponse(status=200)
|
||||
|
||||
|
||||
@event_permission_required('event.settings.payment:write')
|
||||
@event_permission_required('event.settings.general:write')
|
||||
def oauth_disconnect(request, **kwargs):
|
||||
if request.method != "POST":
|
||||
return render(request, 'pretixplugins/stripe/oauth_disconnect.html', {})
|
||||
@@ -399,6 +496,59 @@ class StripeOrderView:
|
||||
}) + ('?paid=yes' if self.order.status == Order.STATUS_PAID else ''))
|
||||
|
||||
|
||||
@method_decorator(xframe_options_exempt, 'dispatch')
|
||||
class ReturnView(StripeOrderView, View):
|
||||
def get(self, request, *args, **kwargs):
|
||||
import stripe
|
||||
|
||||
prov = self.pprov
|
||||
prov._init_api()
|
||||
try:
|
||||
src = stripe.Source.retrieve(request.GET.get('source'), **prov.api_kwargs)
|
||||
except stripe.error.InvalidRequestError:
|
||||
logger.exception('Could not retrieve source')
|
||||
messages.error(self.request, _('Sorry, there was an error in the payment process. Please check the link '
|
||||
'in your emails to continue.'))
|
||||
return redirect_to_url(eventreverse(self.request.event, 'presale:event.index'))
|
||||
|
||||
if src.client_secret != request.GET.get('client_secret'):
|
||||
messages.error(self.request, _('Sorry, there was an error in the payment process. Please check the link '
|
||||
'in your emails to continue.'))
|
||||
return redirect_to_url(eventreverse(self.request.event, 'presale:event.index'))
|
||||
|
||||
with transaction.atomic():
|
||||
self.order.refresh_from_db()
|
||||
self.payment = OrderPayment.objects.select_for_update(of=OF_SELF).get(pk=self.payment.pk)
|
||||
if self.payment.state == OrderPayment.PAYMENT_STATE_CONFIRMED:
|
||||
if 'payment_stripe_token' in request.session:
|
||||
del request.session['payment_stripe_token']
|
||||
return self._redirect_to_order()
|
||||
|
||||
if src.status == 'chargeable':
|
||||
try:
|
||||
prov._charge_source(request, src.id, self.payment)
|
||||
except PaymentException as e:
|
||||
messages.error(request, str(e))
|
||||
return self._redirect_to_order()
|
||||
finally:
|
||||
if 'payment_stripe_token' in request.session:
|
||||
del request.session['payment_stripe_token']
|
||||
elif src.status == 'consumed':
|
||||
# Webhook was faster, wow! ;)
|
||||
if 'payment_stripe_token' in request.session:
|
||||
del request.session['payment_stripe_token']
|
||||
return self._redirect_to_order()
|
||||
elif src.status == 'pending':
|
||||
self.payment.state = OrderPayment.PAYMENT_STATE_PENDING
|
||||
self.payment.info = str(src)
|
||||
self.payment.save()
|
||||
else: # failed or canceled
|
||||
self.payment.fail(info=str(src))
|
||||
messages.error(self.request, _('We had trouble authorizing your card payment. Please try again and '
|
||||
'get in touch with us if this problem persists.'))
|
||||
return self._redirect_to_order()
|
||||
|
||||
|
||||
@method_decorator(xframe_options_exempt, 'dispatch')
|
||||
class ScaView(StripeOrderView, View):
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
#
|
||||
from datetime import timedelta
|
||||
|
||||
from celery.result import AsyncResult
|
||||
from django.conf import settings
|
||||
from django.db import transaction
|
||||
from django.db.models import QuerySet
|
||||
@@ -37,7 +38,6 @@ from rest_framework.reverse import reverse
|
||||
|
||||
from pretix.api.serializers.i18n import I18nAwareModelSerializer
|
||||
from pretix.api.serializers.order import CompatibleJSONField
|
||||
from pretix.helpers.celery import get_task_result
|
||||
|
||||
from ...api.serializers.fields import UploadedFileField
|
||||
from ...base.models import CachedFile, OrderPosition, SalesChannel
|
||||
@@ -257,7 +257,7 @@ class TicketRendererViewSet(viewsets.ViewSet):
|
||||
status=status.HTTP_410_GONE
|
||||
)
|
||||
|
||||
res = get_task_result(kwargs['asyncid'], task_name=bulk_render)
|
||||
res = AsyncResult(kwargs['asyncid'])
|
||||
if res.failed():
|
||||
if isinstance(res.info, dict) and res.info['exc_type'] == 'ExportError':
|
||||
msg = res.info['exc_message']
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { SubEvent } from './i18n'
|
||||
import type { LocalizableString } from '@/pretix/static/pretixbase/js/i18n'
|
||||
import type { I18nString, SubEvent } from './i18n'
|
||||
|
||||
const settingsEl = document.getElementById('api-settings')
|
||||
const { urls } = JSON.parse(settingsEl.textContent || '{}') as { urls: {
|
||||
@@ -60,8 +59,8 @@ export interface Position {
|
||||
order: string
|
||||
positionid: number
|
||||
canceled?: boolean
|
||||
item: { id?: number; name: LocalizableString; internal_name?: string; admission?: boolean }
|
||||
variation: { id?: number; value: LocalizableString } | null
|
||||
item: { id?: number; name: I18nString; internal_name?: string; admission?: boolean }
|
||||
variation: { id?: number; value: I18nString } | null
|
||||
price: string
|
||||
attendee_name: string
|
||||
attendee_name_parts: Record<string, string>
|
||||
@@ -111,8 +110,8 @@ export interface Answer {
|
||||
|
||||
export interface AnswerQuestion {
|
||||
id: number
|
||||
question: LocalizableString
|
||||
help_text?: LocalizableString
|
||||
question: I18nString
|
||||
help_text?: I18nString
|
||||
type: string
|
||||
required: boolean
|
||||
position: number
|
||||
@@ -139,12 +138,12 @@ export interface QuestionOption {
|
||||
id: number
|
||||
identifier: string
|
||||
position: number
|
||||
answer: LocalizableString
|
||||
answer: I18nString
|
||||
}
|
||||
|
||||
export interface Addon {
|
||||
item: { name: LocalizableString; internal_name?: string }
|
||||
variation: { value: LocalizableString } | null
|
||||
item: { name: I18nString; internal_name?: string }
|
||||
variation: { value: I18nString } | null
|
||||
}
|
||||
|
||||
export interface CheckinStatusVariation {
|
||||
|
||||
@@ -2,8 +2,7 @@
|
||||
import { ref, computed, nextTick, onMounted, onUnmounted } from 'vue'
|
||||
import { api } from '../api'
|
||||
import type { CheckinList, Position, RedeemResponse, CheckinStatus, AnswerQuestion } from '../api'
|
||||
import { STRINGS, formatSubevent, formatAnswer } from '../i18n'
|
||||
import { localize_string } from '@/pretix/static/pretixbase/js/i18n'
|
||||
import { STRINGS, i18nstringLocalize, formatSubevent, formatAnswer } from '../i18n'
|
||||
|
||||
import CheckinlistSelect from './checkinlist-select.vue'
|
||||
import SearchresultItem from './searchresult-item.vue'
|
||||
@@ -115,9 +114,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 || localize_string(addon.item.name)} – ${localize_string(addon.variation.value)}`
|
||||
return `+ ${addon.item.internal_name || i18nstringLocalize(addon.item.name)} – ${i18nstringLocalize(addon.variation.value)}`
|
||||
}
|
||||
return '+ ' + (addon.item.internal_name || localize_string(addon.item.name))
|
||||
return '+ ' + (addon.item.internal_name || i18nstringLocalize(addon.item.name))
|
||||
}).join('\n')
|
||||
})
|
||||
|
||||
@@ -126,9 +125,9 @@ const checkResultSubevent = computed(() => formatSubevent(checkResult.value?.pos
|
||||
const checkResultItemvar = computed(() => {
|
||||
if (!checkResult.value?.position) return ''
|
||||
if (checkResult.value.position.variation) {
|
||||
return `${localize_string(checkResult.value.position.item.name)} – ${localize_string(checkResult.value.position.variation.value)}`
|
||||
return `${i18nstringLocalize(checkResult.value.position.item.name)} – ${i18nstringLocalize(checkResult.value.position.variation.value)}`
|
||||
}
|
||||
return localize_string(checkResult.value.position.item.name)
|
||||
return i18nstringLocalize(checkResult.value.position.item.name)
|
||||
})
|
||||
|
||||
const checkResultText = computed(() => {
|
||||
@@ -317,9 +316,9 @@ async function check (
|
||||
if (!answers.value[q.id.toString()]) {
|
||||
answers.value[q.id.toString()] = ''
|
||||
}
|
||||
;(q as AnswerQuestion).question = localize_string(q.question)
|
||||
;(q as AnswerQuestion).question = i18nstringLocalize(q.question)
|
||||
for (const o of q.options) {
|
||||
;(o as { answer: string }).answer = localize_string(o.answer)
|
||||
;(o as { answer: string }).answer = i18nstringLocalize(o.answer)
|
||||
}
|
||||
}
|
||||
nextTick(() => {
|
||||
@@ -411,7 +410,7 @@ onUnmounted(() => {
|
||||
span(v-for="a in checkResult.position.answers")
|
||||
span(v-if="a.question.show_during_checkin")
|
||||
br
|
||||
strong {{ localize_string(a.question.question) }}:
|
||||
strong {{ i18nstringLocalize(a.question.question) }}:
|
||||
| {{ formatAnswer(a.answer, a.question) }}
|
||||
strong(v-for="t in checkResult.checkin_texts")
|
||||
br
|
||||
|
||||
+3
-4
@@ -1,8 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue'
|
||||
import type { Position } from '../api'
|
||||
import { STRINGS, formatSubevent } from '../i18n'
|
||||
import { localize_string } from '@/pretix/static/pretixbase/js/i18n'
|
||||
import { STRINGS, i18nstringLocalize, formatSubevent } from '../i18n'
|
||||
|
||||
const props = defineProps<{
|
||||
position: Position
|
||||
@@ -23,9 +22,9 @@ const status = computed(() => {
|
||||
|
||||
const itemvar = computed(() => {
|
||||
if (props.position.variation) {
|
||||
return `${localize_string(props.position.item.name)} – ${localize_string(props.position.variation.value)}`
|
||||
return `${i18nstringLocalize(props.position.item.name)} – ${i18nstringLocalize(props.position.variation.value)}`
|
||||
}
|
||||
return localize_string(props.position.item.name)
|
||||
return i18nstringLocalize(props.position.item.name)
|
||||
})
|
||||
|
||||
const subevent = computed(() => formatSubevent(props.position.subevent))
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
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'
|
||||
@@ -12,6 +9,27 @@ 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.'),
|
||||
@@ -65,7 +83,7 @@ export interface SubEvent {
|
||||
|
||||
export function formatSubevent (subevent: SubEvent | null | undefined): string {
|
||||
if (!subevent) return ''
|
||||
const name = localize_string(subevent.name)
|
||||
const name = i18nstringLocalize(subevent.name)
|
||||
const date = moment.utc(subevent.date_from).tz(timezone).format(datetimeFormat)
|
||||
return `${name} · ${date}`
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
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>
|
||||
|
||||
@@ -221,7 +221,7 @@
|
||||
<div role="cell" class="download-desktop">
|
||||
{% if line in tickets_with_download %}
|
||||
{% for b in download_buttons %}
|
||||
<form action="{% if position_page %}{% eventurl event "presale:event.order.position.download" secret=position_page.web_secret order=order.code output=b.identifier pid=line.pk position=position_page.positionid %}{% else %}{% eventurl event "presale:event.order.download" secret=order.secret order=order.code output=b.identifier position=line.pk %}{% endif %}"
|
||||
<form action="{% if position_page and line.addon_to %}{% eventurl event "presale:event.order.position.download" secret=line.addon_to.web_secret order=order.code output=b.identifier pid=line.pk position=line.addon_to.positionid %}{% elif position_page %}{% eventurl event "presale:event.order.position.download" secret=line.web_secret order=order.code output=b.identifier pid=line.pk position=line.positionid %}{% else %}{% eventurl event "presale:event.order.download" secret=order.secret order=order.code output=b.identifier position=line.pk %}{% endif %}"
|
||||
method="post" data-asynctask data-asynctask-download class="download-btn-form{% if b.javascript_required %} requirejs{% endif %}">
|
||||
{% csrf_token %}
|
||||
<button type="submit"
|
||||
@@ -364,7 +364,7 @@
|
||||
<code>{{ gc.secret }}</code>
|
||||
<strong>{% trans "Current value:" %}</strong>
|
||||
{{ gc.value|money:gc.currency }}
|
||||
<a href="{% if position_page %}{% eventurl event "presale:event.order.position.giftcard" secret=position_page.web_secret order=order.code pk=gc.pk position=line.positionid %}{% else %}{% eventurl event "presale:event.order.giftcard" secret=order.secret order=order.code pk=gc.pk %}{% endif %}"
|
||||
<a href="{% if position_page and line.addon_to %}{% eventurl event "presale:event.order.position.giftcard" secret=line.addon_to.web_secret order=order.code pk=gc.pk position=line.addon_to.positionid %}{% elif position_page %}{% eventurl event "presale:event.order.position.giftcard" secret=line.web_secret order=order.code pk=gc.pk position=line.positionid %}{% else %}{% eventurl event "presale:event.order.giftcard" secret=order.secret order=order.code pk=gc.pk %}{% endif %}"
|
||||
class="btn btn-default btn-sm">
|
||||
<span class="fa fa-eye" aria-hidden="true"></span>
|
||||
{% trans "Details" %}
|
||||
|
||||
@@ -61,7 +61,7 @@
|
||||
{% elif tickets_with_download|length == 1 %}
|
||||
<div>
|
||||
{% for b in download_buttons %}
|
||||
<form action="{% if position_page %}{% eventurl event "presale:event.order.position.download" secret=position_page.web_secret order=order.code output=b.identifier pid=tickets_with_download.0.pk position=position_page.positionid %}{% else %}{% eventurl event "presale:event.order.download" secret=order.secret order=order.code output=b.identifier position=tickets_with_download.0.pk %}{% endif %}"
|
||||
<form action="{% if position_page and tickets_with_download.0.addon_to %}{% eventurl event "presale:event.order.position.download" secret=tickets_with_download.0.addon_to.web_secret order=order.code output=b.identifier pid=tickets_with_download.0.pk position=tickets_with_download.0.addon_to.positionid %}{% elif position_page %}{% eventurl event "presale:event.order.position.download" secret=tickets_with_download.0.web_secret order=order.code output=b.identifier pid=tickets_with_download.0.pk position=tickets_with_download.0.positionid %}{% else %}{% eventurl event "presale:event.order.download" secret=order.secret order=order.code output=b.identifier position=tickets_with_download.0.pk %}{% endif %}"
|
||||
method="post" data-asynctask data-asynctask-download
|
||||
class="download-btn-form{% if b.javascript_required %} requirejs{% endif %}">
|
||||
{% csrf_token %}
|
||||
|
||||
@@ -4,14 +4,14 @@
|
||||
{% if answer %}
|
||||
{% if answer.file %}
|
||||
<span class="fa fa-file" aria-hidden="true"></span>
|
||||
<a href="{% answer_url request answer %}">
|
||||
<a href="{{ answer.frontend_file_url }}?token={% answer_token request answer %}">
|
||||
{{ answer.file_name }}
|
||||
</a>
|
||||
{% if answer.is_image %}
|
||||
<br>
|
||||
<a href="{% answer_url request answer %}" data-lightbox="order"
|
||||
<a href="{{ answer.frontend_file_url }}?token={% answer_token request answer %}" data-lightbox="order"
|
||||
class="answer-thumb">
|
||||
<img src="{% answer_url request answer %}" alt="{% trans "The image you previously uploaded" %}">
|
||||
<img src="{{ answer.frontend_file_url }}?token={% answer_token request answer %}" alt="{% trans "The image you previously uploaded" %}">
|
||||
</a>
|
||||
{% endif %}
|
||||
{% elif question.type == "M" %}
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
<dd class="text-muted">{% include "pretixpresale/event/fragment_order_status.html" with order=order event=request.event %}</dd>
|
||||
</dl>
|
||||
{% eventsignal event "pretix.presale.signals.position_info_top" order=order position=position request=request %}
|
||||
{% include "pretixpresale/event/fragment_downloads.html" with position_page=position %}
|
||||
{% include "pretixpresale/event/fragment_downloads.html" with position_page=True %}
|
||||
<div class="panel panel-primary cart">
|
||||
<div class="panel-heading">
|
||||
<h3 class="panel-title">
|
||||
@@ -38,7 +38,7 @@
|
||||
</h3>
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
{% include "pretixpresale/event/fragment_cart.html" with cart=cart event=request.event download=can_download position_page=position editable=False hide_prices=request.event.settings.hide_prices_from_attendees %}
|
||||
{% include "pretixpresale/event/fragment_cart.html" with cart=cart event=request.event download=can_download position_page=True editable=False hide_prices=request.event.settings.hide_prices_from_attendees %}
|
||||
</div>
|
||||
</div>
|
||||
<div class="panel panel-primary">
|
||||
|
||||
@@ -135,6 +135,9 @@ event_patterns = [
|
||||
re_path(r'^order/(?P<order>[^/]+)/(?P<secret>[A-Za-z0-9]+)/pay/change',
|
||||
pretix.presale.views.order.OrderPayChangeMethod.as_view(),
|
||||
name='event.order.pay.change'),
|
||||
re_path(r'^order/(?P<order>[^/]+)/(?P<secret>[A-Za-z0-9]+)/answer/(?P<answer>[^/]+)/$',
|
||||
pretix.presale.views.order.AnswerDownload.as_view(),
|
||||
name='event.order.download.answer'),
|
||||
re_path(r'^order/(?P<order>[^/]+)/(?P<secret>[A-Za-z0-9]+)/download/(?P<output>[^/]+)$',
|
||||
pretix.presale.views.order.OrderDownload.as_view(),
|
||||
name='event.order.download.combined'),
|
||||
@@ -164,9 +167,6 @@ event_patterns = [
|
||||
pretix.presale.views.order.OrderPositionModify.as_view(),
|
||||
name='event.order.position.modify'),
|
||||
|
||||
re_path(r'^answer/(?P<answer>[^/]+)/$',
|
||||
pretix.presale.views.order.AnswerDownload.as_view(),
|
||||
name='event.download.answer'),
|
||||
re_path(r'^ical/?$',
|
||||
pretix.presale.views.event.EventIcalDownload.as_view(),
|
||||
name='event.ical.download'),
|
||||
|
||||
@@ -247,7 +247,8 @@ def _items_from_post_data(request, warn_if_empty=True):
|
||||
pass
|
||||
|
||||
items = []
|
||||
|
||||
if 'raw' in request.POST:
|
||||
items += json.loads(request.POST.get("raw"))
|
||||
for key, values in req_items:
|
||||
for value in values:
|
||||
try:
|
||||
@@ -262,7 +263,6 @@ def _items_from_post_data(request, warn_if_empty=True):
|
||||
if len(items) == 0 and warn_if_empty:
|
||||
messages.warning(request, _('You did not select any products.'))
|
||||
return []
|
||||
|
||||
return items
|
||||
|
||||
|
||||
|
||||
@@ -83,7 +83,8 @@ class CheckoutView(View):
|
||||
return self.redirect(previous_step.get_step_url(request) if previous_step else self.get_index_url(request))
|
||||
|
||||
if 'step' not in kwargs:
|
||||
return self.redirect(step.get_step_url(request))
|
||||
utm_params = {k: v for k, v in request.GET.items() if k.startswith("utm_")}
|
||||
return self.redirect(step.get_step_url(request) + '?' + urlencode(utm_params))
|
||||
is_selected = (step.identifier == kwargs.get('step', ''))
|
||||
|
||||
if not is_asyncaction_call and not is_selected and not step.is_completed(request, warn=not is_selected):
|
||||
@@ -104,6 +105,6 @@ class CheckoutView(View):
|
||||
raise Http404()
|
||||
|
||||
def redirect(self, url):
|
||||
params = {k: v for k, v in self.request.GET.items() if k in ("cart_id", "gclid", "_gl") or k.startswith("utm_")}
|
||||
url += ('&' if '?' in url else '?') + urlencode(params)
|
||||
if 'cart_id' in self.request.GET:
|
||||
url += ('&' if '?' in url else '?') + 'cart_id=' + quote(self.request.GET.get('cart_id'))
|
||||
return redirect_to_url(url)
|
||||
@@ -26,7 +26,8 @@ from binascii import unhexlify
|
||||
from datetime import timedelta
|
||||
from urllib.parse import parse_qs, urlencode, urlparse, urlunparse
|
||||
|
||||
from Crypto.PublicKey import RSA
|
||||
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey
|
||||
from cryptography.hazmat.primitives.serialization import load_pem_public_key
|
||||
from django.db import transaction
|
||||
from django.http import Http404, HttpResponse, JsonResponse
|
||||
from django.shortcuts import redirect, render
|
||||
@@ -498,7 +499,9 @@ class KeysView(View):
|
||||
def get(self, request, *args, **kwargs):
|
||||
privkey, pubkey = _get_or_create_server_keypair(request.organizer)
|
||||
kid = hashlib.sha256(pubkey.encode()).hexdigest()[:16]
|
||||
pubkey = RSA.import_key(pubkey)
|
||||
public_key = load_pem_public_key(pubkey.encode())
|
||||
assert isinstance(public_key, RSAPublicKey)
|
||||
public_numbers = public_key.public_numbers()
|
||||
|
||||
return JsonResponse({
|
||||
'keys': [
|
||||
@@ -507,8 +510,8 @@ class KeysView(View):
|
||||
'alg': 'RS256',
|
||||
'kid': kid,
|
||||
'use': 'sig',
|
||||
'e': self._encode_int(pubkey.e).decode().rstrip("="),
|
||||
'n': self._encode_int(pubkey.n).decode().rstrip("="),
|
||||
'e': self._encode_int(public_numbers.e).decode().rstrip("="),
|
||||
'n': self._encode_int(public_numbers.n).decode().rstrip("="),
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
@@ -1159,23 +1159,25 @@ class OrderCancelDo(EventViewMixin, OrderDetailMixin, AsyncAction, View):
|
||||
|
||||
|
||||
@method_decorator(xframe_options_exempt, 'dispatch')
|
||||
class AnswerDownload(EventViewMixin, View):
|
||||
class AnswerDownload(EventViewMixin, OrderDetailMixin, View):
|
||||
def get(self, request, *args, **kwargs):
|
||||
answid = kwargs.get('answer')
|
||||
token = request.GET.get('token', '')
|
||||
|
||||
answer = get_object_or_404(
|
||||
QuestionAnswer,
|
||||
Q(orderposition__order__event=self.request.event) | Q(order__event=self.request.event),
|
||||
Q(orderposition__order=self.order) | Q(order=self.order),
|
||||
id=answid,
|
||||
)
|
||||
if not answer.file or not check_token(request, answer, token):
|
||||
if not answer.file:
|
||||
raise Http404()
|
||||
if not check_token(request, answer, token):
|
||||
raise Http404(_("This link is no longer valid. Please go back, refresh the page, and try again."))
|
||||
|
||||
ftype, ignored = mimetypes.guess_type(answer.file.name)
|
||||
resp = FileResponse(answer.file, content_type=ftype or 'application/binary')
|
||||
resp['Content-Disposition'] = 'attachment; filename="{}-{}-{}-{}"'.format(
|
||||
self.request.event.slug.upper(), answer.associated_order.code,
|
||||
self.request.event.slug.upper(), self.order.code,
|
||||
answer.orderposition.positionid if answer.orderposition else '',
|
||||
os.path.basename(answer.file.name).split('.', 1)[1]
|
||||
)
|
||||
|
||||
@@ -57,7 +57,6 @@ 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(
|
||||
|
||||
+1
-11
@@ -37,7 +37,6 @@ import configparser
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import warnings
|
||||
from json import loads
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
@@ -384,7 +383,6 @@ if HAS_CELERY:
|
||||
CELERY_RESULT_BACKEND_TRANSPORT_OPTIONS = loads(config.get('celery', 'backend_transport_options'))
|
||||
CELERY_BROKER_CONNECTION_RETRY_ON_STARTUP = True
|
||||
|
||||
_redis_types = ("redis://", "rediss://", "sentinel://", "redis+socket://")
|
||||
if CELERY_BROKER_URL.startswith("amqp://"):
|
||||
# https://docs.celeryq.dev/en/latest/userguide/routing.html#routing-options-rabbitmq-priorities
|
||||
# Enable priorities for all queues
|
||||
@@ -397,9 +395,7 @@ if HAS_CELERY:
|
||||
PRIORITY_CELERY_HIGHEST_FUNC = max
|
||||
# Set default
|
||||
CELERY_TASK_DEFAULT_PRIORITY = PRIORITY_CELERY_MID
|
||||
warnings.warn("pretix only officially supports running with redis as a celery task broker. "
|
||||
"Unexpected behavior might occur.")
|
||||
elif any(CELERY_BROKER_URL.startswith(p) for p in _redis_types):
|
||||
elif CELERY_BROKER_URL.startswith("redis://"):
|
||||
# https://docs.celeryq.dev/en/latest/userguide/routing.html#redis-message-priorities
|
||||
CELERY_BROKER_TRANSPORT_OPTIONS.update({
|
||||
"queue_order_strategy": "priority",
|
||||
@@ -421,12 +417,6 @@ if HAS_CELERY:
|
||||
PRIORITY_CELERY_HIGH = 0
|
||||
PRIORITY_CELERY_LOWEST_FUNC = min
|
||||
PRIORITY_CELERY_HIGHEST_FUNC = max
|
||||
warnings.warn("pretix only officially supports running with redis as a celery task broker. "
|
||||
"Unexpected behavior might occur.")
|
||||
|
||||
if not any(CELERY_RESULT_BACKEND.startswith(p) for p in _redis_types):
|
||||
warnings.warn("pretix only officially supports running with redis as a celery task backend. "
|
||||
"Unexpected behavior might occur.")
|
||||
else:
|
||||
CELERY_TASK_ALWAYS_EAGER = True
|
||||
PRIORITY_CELERY_LOW = 0
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
<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
|
||||
globalThis.gettext = (msgid) => {
|
||||
function gettext (msgid) {
|
||||
if (typeof django !== 'undefined' && typeof django.gettext !== 'undefined') {
|
||||
return django.gettext(msgid)
|
||||
}
|
||||
return msgid
|
||||
}
|
||||
|
||||
globalThis.ngettext = (singular, plural, count) => {
|
||||
function ngettext (singular, plural, count) {
|
||||
if (typeof django !== 'undefined' && typeof django.ngettext !== 'undefined') {
|
||||
return django.ngettext(singular, plural, count)
|
||||
}
|
||||
return plural
|
||||
}
|
||||
|
||||
globalThis.pgettext = (context, msgid) => {
|
||||
function pgettext (context, msgid) {
|
||||
if (typeof django !== 'undefined' && typeof django.pgettext !== 'undefined') {
|
||||
return django.pgettext(context, msgid)
|
||||
}
|
||||
return msgid
|
||||
}
|
||||
|
||||
globalThis.interpolate = (fmt, obj, named) => {
|
||||
function 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()) })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
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];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
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,3 +1,5 @@
|
||||
/* global gettext, pgettext */
|
||||
|
||||
export const TEXTS = {
|
||||
and: gettext('All of the conditions below (AND)'),
|
||||
or: gettext('At least one of the conditions below (OR)'),
|
||||
|
||||
@@ -87,7 +87,7 @@ fabric.Textcontainer = fabric.util.createClass(fabric.Rect, {
|
||||
fontSize: fontSize,
|
||||
lineHeight: this.lineHeight,
|
||||
fill: this.fill,
|
||||
fontFamily: this.fontFamily || '',
|
||||
fontFamily: this.fontFamily,
|
||||
fontWeight: this.fontWeight,
|
||||
fontStyle: this.fontStyle,
|
||||
text: text,
|
||||
@@ -377,7 +377,7 @@ var editor = {
|
||||
o.set('fill', 'rgb(' + d.color[0] + ',' + d.color[1] + ',' + d.color[2] + ')')
|
||||
o.set('fontSize', editor._pt2px(d.fontsize))
|
||||
o.set('lineHeight', d.lineheight || 1)
|
||||
o.set('fontFamily', d.fontfamily || '')
|
||||
o.set('fontFamily', d.fontfamily)
|
||||
o.set('fontWeight', d.bold ? 'bold' : 'normal')
|
||||
o.set('fontStyle', d.italic ? 'italic' : 'normal')
|
||||
o.content = d.content
|
||||
@@ -407,7 +407,7 @@ var editor = {
|
||||
o.set('fill', 'rgb(' + d.color[0] + ',' + d.color[1] + ',' + d.color[2] + ')')
|
||||
o.set('fontSize', editor._pt2px(d.fontsize))
|
||||
o.set('lineHeight', d.lineheight || 1)
|
||||
o.set('fontFamily', d.fontfamily || '')
|
||||
o.set('fontFamily', d.fontfamily)
|
||||
o.set('fontWeight', d.bold ? 'bold' : 'normal')
|
||||
o.set('fontStyle', d.italic ? 'italic' : 'normal')
|
||||
o.downward = d.downward || false
|
||||
@@ -812,7 +812,7 @@ var editor = {
|
||||
o.set('fill', $('#toolbox-col').val())
|
||||
o.set('fontSize', editor._pt2px($('#toolbox-fontsize').val()))
|
||||
o.set('lineHeight', $('#toolbox-lineheight').val() || 1)
|
||||
o.set('fontFamily', $('#toolbox-fontfamily').val() || '')
|
||||
o.set('fontFamily', $('#toolbox-fontfamily').val())
|
||||
o.set('fontWeight', $('#toolbox').find('button[data-action=bold]').is('.active') ? 'bold' : 'normal')
|
||||
o.set('fontStyle', $('#toolbox').find('button[data-action=italic]').is('.active') ? 'italic' : 'normal')
|
||||
var align = $('#toolbox-align').find('.active').attr('data-action')
|
||||
@@ -856,7 +856,7 @@ var editor = {
|
||||
o.set('fill', $('#toolbox-col').val())
|
||||
o.set('fontSize', editor._pt2px($('#toolbox-fontsize').val()))
|
||||
o.set('lineHeight', $('#toolbox-lineheight').val() || 1)
|
||||
o.set('fontFamily', $('#toolbox-fontfamily').val() || '')
|
||||
o.set('fontFamily', $('#toolbox-fontfamily').val())
|
||||
o.set('fontWeight', $('#toolbox').find('button[data-action=bold]').is('.active') ? 'bold' : 'normal')
|
||||
o.set('fontStyle', $('#toolbox').find('button[data-action=italic]').is('.active') ? 'italic' : 'normal')
|
||||
var align = $('#toolbox-align').find('.active').attr('data-action')
|
||||
|
||||
@@ -152,9 +152,12 @@ export function createWidgetStore (config: {
|
||||
return ''
|
||||
},
|
||||
additionalURLParams (): string {
|
||||
if (!window.location.search.includes('utm_')) {
|
||||
return ''
|
||||
}
|
||||
const params = new URLSearchParams(window.location.search)
|
||||
for (const key of [...params.keys()]) {
|
||||
if (!key.startsWith('utm_') && key !== 'gclid' && key !== '_gl') {
|
||||
for (const [key] of params.entries()) {
|
||||
if (!key.startsWith('utm_')) {
|
||||
params.delete(key)
|
||||
}
|
||||
}
|
||||
@@ -162,7 +165,10 @@ export function createWidgetStore (config: {
|
||||
},
|
||||
newTabTarget (): string {
|
||||
let url = this.subevent ? `${this.targetUrl}${this.subevent}/` : this.targetUrl
|
||||
const parameters = this.additionalURLParams + this.consentParameter
|
||||
let parameters = this.consentParameter
|
||||
if (this.additionalURLParams) {
|
||||
parameters += `&${this.additionalURLParams}`
|
||||
}
|
||||
if (parameters) {
|
||||
url += '?' + parameters.replace(/^&/, '')
|
||||
}
|
||||
@@ -193,9 +199,8 @@ export function createWidgetStore (config: {
|
||||
if (!this.cartExists) {
|
||||
checkoutUrl += 'checkout/start'
|
||||
}
|
||||
const parameters = this.additionalURLParams + this.consentParameter
|
||||
if (parameters) {
|
||||
checkoutUrl += '?' + parameters.replace(/^&/, '')
|
||||
if (this.additionalURLParams) {
|
||||
checkoutUrl += `?${this.additionalURLParams}`
|
||||
}
|
||||
|
||||
let formTarget = `${this.targetUrl}w/${globalWidgetId}/cart/add?iframe=1&next=${encodeURIComponent(checkoutUrl)}`
|
||||
|
||||
@@ -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, Gate, Organizer, Team, User
|
||||
from pretix.base.models import Device, Event, Organizer, Team, User
|
||||
from pretix.base.models.devices import generate_api_token
|
||||
|
||||
|
||||
@@ -132,16 +132,6 @@ 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')
|
||||
|
||||
@@ -42,8 +42,7 @@ from django.utils.timezone import now
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
from pretix.base.models import (
|
||||
CachedFile, Event, Organizer, ScheduledEventExport,
|
||||
ScheduledOrganizerExport, User,
|
||||
CachedFile, Event, ScheduledEventExport, ScheduledOrganizerExport, User,
|
||||
)
|
||||
|
||||
SAMPLE_EXPORTER_CONFIG = {
|
||||
@@ -919,10 +918,6 @@ def test_organizer_edit_restrictions(client, event, organizer, user, team):
|
||||
team1.limit_events.add(event1)
|
||||
team1.members.add(user)
|
||||
|
||||
organizer2 = Organizer.objects.create(name='Dummy2', slug='dummy2')
|
||||
org2_team = organizer2.teams.create(all_events=True, all_event_permissions=True, name="Admins")
|
||||
org2_team.members.add(user)
|
||||
|
||||
t = team.tokens.create(name='Foo')
|
||||
client.credentials(HTTP_AUTHORIZATION='Token ' + t.token)
|
||||
|
||||
|
||||
@@ -1,96 +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_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
|
||||
@@ -872,51 +872,6 @@ def test_item_create_with_addon(token_client, organizer, event, item, category,
|
||||
with scopes_disabled():
|
||||
assert 2 == Item.objects.all().count()
|
||||
|
||||
resp = token_client.post(
|
||||
'/api/v1/organizers/{}/events/{}/items/'.format(organizer.slug, event.slug),
|
||||
{
|
||||
"category": category.pk,
|
||||
"name": {
|
||||
"en": "Ticket"
|
||||
},
|
||||
"active": True,
|
||||
"description": None,
|
||||
"default_price": "23.00",
|
||||
"free_price": False,
|
||||
"tax_rate": "19.00",
|
||||
"tax_rule": taxrule.pk,
|
||||
"admission": True,
|
||||
"issue_giftcard": False,
|
||||
"position": 0,
|
||||
"picture": None,
|
||||
"available_from": None,
|
||||
"available_until": None,
|
||||
"require_voucher": False,
|
||||
"hide_without_voucher": False,
|
||||
"allow_cancel": True,
|
||||
"min_per_order": None,
|
||||
"max_per_order": None,
|
||||
"checkin_attention": False,
|
||||
"checkin_text": None,
|
||||
"has_variations": True,
|
||||
"addons": [
|
||||
{
|
||||
"addon_category": category.pk,
|
||||
"min_count": 0,
|
||||
"max_count": 0,
|
||||
"position": 0,
|
||||
"multi_allowed": False,
|
||||
"price_included": True
|
||||
}
|
||||
]
|
||||
},
|
||||
format='json'
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
assert resp.content.decode() == '{"addons":["The maximum count needs to be greater than zero."]}'
|
||||
with scopes_disabled():
|
||||
assert 2 == Item.objects.all().count()
|
||||
|
||||
resp = token_client.post(
|
||||
'/api/v1/organizers/{}/events/{}/items/'.format(organizer.slug, event.slug),
|
||||
{
|
||||
@@ -1143,48 +1098,6 @@ def test_item_create_with_bundle(token_client, organizer, event, item, category,
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
assert resp.content.decode() == '{"bundles":["The chosen variation does not belong to this item."]}'
|
||||
with scopes_disabled():
|
||||
v = item2.variations.create(value="foo")
|
||||
|
||||
resp = token_client.post(
|
||||
'/api/v1/organizers/{}/events/{}/items/'.format(organizer.slug, event.slug),
|
||||
{
|
||||
"category": category.pk,
|
||||
"name": {
|
||||
"en": "Ticket"
|
||||
},
|
||||
"active": True,
|
||||
"description": None,
|
||||
"default_price": "23.00",
|
||||
"free_price": False,
|
||||
"tax_rate": "19.00",
|
||||
"tax_rule": taxrule.pk,
|
||||
"admission": True,
|
||||
"position": 0,
|
||||
"picture": None,
|
||||
"available_from": None,
|
||||
"available_until": None,
|
||||
"require_voucher": False,
|
||||
"hide_without_voucher": False,
|
||||
"allow_cancel": True,
|
||||
"min_per_order": None,
|
||||
"max_per_order": None,
|
||||
"checkin_attention": False,
|
||||
"checkin_text": None,
|
||||
"has_variations": True,
|
||||
"bundles": [
|
||||
{
|
||||
"bundled_item": item.pk,
|
||||
"bundled_variation": None,
|
||||
"count": 0,
|
||||
"designated_price": "3.00",
|
||||
}
|
||||
]
|
||||
},
|
||||
format='json'
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
assert resp.content.decode() == '{"bundles":["The count needs to be greater than zero."]}'
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
|
||||
@@ -255,12 +255,6 @@ 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),
|
||||
@@ -326,13 +320,6 @@ 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'))
|
||||
|
||||
@@ -107,34 +107,29 @@ def test_run_success(token_client, order, organizer, team, event):
|
||||
event.date_from = now() - timedelta(days=91)
|
||||
event.date_to = now() - timedelta(days=90)
|
||||
event.save()
|
||||
export_resp = token_client.post(
|
||||
resp = token_client.post(
|
||||
'/api/v1/organizers/{}/events/{}/shredders/export/'.format(organizer.slug, event.slug),
|
||||
data={
|
||||
'shredders': ['order_emails']
|
||||
}, format='json'
|
||||
)
|
||||
assert export_resp.status_code == 202
|
||||
assert "download" in export_resp.data
|
||||
assert "shred" in export_resp.data
|
||||
assert resp.status_code == 202
|
||||
assert "download" in resp.data
|
||||
assert "shred" in resp.data
|
||||
|
||||
download_resp = token_client.get("/" + export_resp.data["download"].split("/", 3)[3])
|
||||
assert download_resp.status_code == 200
|
||||
assert download_resp["Content-Type"] == "application/zip"
|
||||
resp2 = token_client.get("/" + resp.data["download"].split("/", 3)[3])
|
||||
assert resp2.status_code == 200
|
||||
assert resp2["Content-Type"] == "application/zip"
|
||||
|
||||
status_resp = token_client.get("/" + export_resp.data["shred"].split("/", 3)[3].replace("/shred/", "/status/"))
|
||||
assert status_resp.status_code == 404 # cannot get the status of a shred task that does not exists
|
||||
resp3 = token_client.post("/" + resp.data["shred"].split("/", 3)[3])
|
||||
assert resp3.status_code == 202
|
||||
assert "status" in resp3.data
|
||||
|
||||
shred_resp = token_client.post("/" + export_resp.data["shred"].split("/", 3)[3])
|
||||
assert shred_resp.status_code == 202
|
||||
assert "status" in shred_resp.data
|
||||
resp4 = token_client.get("/" + resp3.data["status"].split("/", 3)[3])
|
||||
assert resp4.status_code == 410 # because we have no celery
|
||||
|
||||
assert export_resp.data['shred'].split("/")[11] != shred_resp.data['status'].split("/")[11] # shredding should have a different task id than exporting
|
||||
|
||||
status_resp = token_client.get("/" + shred_resp.data["status"].split("/", 3)[3])
|
||||
assert status_resp.status_code == 410 # because we have no celery
|
||||
|
||||
download_resp = token_client.get("/" + export_resp.data["download"].split("/", 3)[3])
|
||||
assert download_resp.status_code == 404 # shredded now
|
||||
resp2 = token_client.get("/" + resp.data["download"].split("/", 3)[3])
|
||||
assert resp2.status_code == 404 # shredded now
|
||||
|
||||
order.refresh_from_db()
|
||||
assert not order.email
|
||||
|
||||
@@ -162,32 +162,6 @@ def test_event_export_schedule(client, env):
|
||||
assert env[0].scheduled_exports.count() == 0
|
||||
|
||||
|
||||
@pytest.mark.django_db(transaction=True)
|
||||
def test_event_export_schedule_copy_new_owner(client, env):
|
||||
env[2].all_events = True
|
||||
env[2].save()
|
||||
user2 = User.objects.create_user("dummy2@dummy.dummy", "dummy")
|
||||
|
||||
s1 = ScheduledEventExport(event=env[0], owner=user2, export_identifier="itemdata")
|
||||
s1.schedule_rrule = "DTSTART:20230118T000000\nRRULE:FREQ=DAILY;INTERVAL=1;WKST=MO"
|
||||
s1.schedule_rrule_time = datetime.time(2, 30, 0)
|
||||
s1.error_counter = 5
|
||||
s1.mail_subject = "RULE1"
|
||||
s1.mail_template = "RULE1 Text"
|
||||
s1.save()
|
||||
|
||||
client.login(email="dummy@dummy.dummy", password="dummy")
|
||||
response = client.get(f"/control/event/dummy/dummy/orders/export/?identifier=itemdata&scheduled_copy_from={s1.pk}")
|
||||
doc = BeautifulSoup(response.content, "lxml")
|
||||
form_data = extract_form_fields(doc.select("form[data-asynctask]")[0])
|
||||
form_data["schedule"] = "save"
|
||||
|
||||
client.post(f"/control/event/dummy/dummy/orders/export/?identifier=itemdata&scheduled_copy_from={s1.pk}", form_data)
|
||||
new = ScheduledEventExport.objects.get(pk__gt=s1.pk)
|
||||
assert new.owner == env[1]
|
||||
assert new.error_counter == 0
|
||||
|
||||
|
||||
@pytest.mark.django_db(transaction=True)
|
||||
def test_event_limited_permission(client, env):
|
||||
env[2].all_event_permissions = False
|
||||
@@ -356,33 +330,6 @@ def test_organizer_export_schedule(client, env):
|
||||
assert env[0].organizer.scheduled_exports.count() == 0
|
||||
|
||||
|
||||
@pytest.mark.django_db(transaction=True)
|
||||
def test_organizer_export_schedule_copy_new_owner(client, env):
|
||||
env[2].all_organizer_permissions = True
|
||||
env[2].save()
|
||||
user2 = User.objects.create_user("dummy2@dummy.dummy", "dummy")
|
||||
|
||||
s1 = ScheduledOrganizerExport(organizer=env[0].organizer, owner=user2, export_identifier="eventdata")
|
||||
s1.schedule_rrule = "DTSTART:20230118T000000\nRRULE:FREQ=DAILY;INTERVAL=1;WKST=MO"
|
||||
s1.schedule_rrule_time = datetime.time(2, 30, 0)
|
||||
s1.error_counter = 5
|
||||
s1.mail_subject = "RULE1"
|
||||
s1.mail_template = "RULE1 Text"
|
||||
s1.export_form_data = {"all_events": True}
|
||||
s1.save()
|
||||
|
||||
client.login(email="dummy@dummy.dummy", password="dummy")
|
||||
response = client.get(f"/control/organizer/dummy/export/?identifier=eventdata&scheduled_copy_from={s1.pk}")
|
||||
doc = BeautifulSoup(response.content, "lxml")
|
||||
form_data = extract_form_fields(doc.select("form[data-asynctask]")[0])
|
||||
form_data["schedule"] = "save"
|
||||
|
||||
client.post(f"/control/organizer/dummy/export/?identifier=eventdata&scheduled_copy_from={s1.pk}", form_data)
|
||||
new = ScheduledOrganizerExport.objects.get(pk__gt=s1.pk)
|
||||
assert new.owner == env[1]
|
||||
assert new.error_counter == 0
|
||||
|
||||
|
||||
@pytest.mark.django_db(transaction=True)
|
||||
def test_organizer_limited_permission(client, env):
|
||||
env[2].all_organizer_permissions = False
|
||||
|
||||
@@ -1307,20 +1307,7 @@ class SubEventsTest(SoupTest):
|
||||
for se in [self.subevent1, self.subevent2]:
|
||||
assert se.checkinlist_set.count() == 1
|
||||
|
||||
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):
|
||||
def test_edit_bulk_lists_keep_mixed(self):
|
||||
with scopes_disabled():
|
||||
self.subevent1.checkinlist_set.create(event=self.event1, name="C1")
|
||||
self.subevent2.checkinlist_set.create(event=self.event1, name="C2")
|
||||
@@ -1328,18 +1315,4 @@ class SubEventsTest(SoupTest):
|
||||
'__ALL': 'on',
|
||||
}, follow=True)
|
||||
fields = extract_form_fields(doc)
|
||||
|
||||
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"
|
||||
assert 'checkinlist_set-TOTAL_FORMS' not in fields
|
||||
@@ -26,7 +26,6 @@ from decimal import Decimal
|
||||
import pytest
|
||||
from django.utils.timezone import now
|
||||
from django_scopes import scopes_disabled
|
||||
from stripe import StripeObject
|
||||
|
||||
from pretix.base.models import (
|
||||
Event, Order, OrderPayment, OrderRefund, Organizer, Team, User,
|
||||
@@ -56,7 +55,7 @@ def env():
|
||||
|
||||
|
||||
def get_test_charge(order: Order):
|
||||
return StripeObject.construct_from({
|
||||
return {
|
||||
"id": "ch_18TY6GGGWE2Is8TZHanef25",
|
||||
"object": "charge",
|
||||
"amount": 1337,
|
||||
@@ -91,59 +90,35 @@ def get_test_charge(order: Order):
|
||||
"total_count": 0
|
||||
},
|
||||
"shipping": None,
|
||||
"payment_intent": {
|
||||
"id": "pi_123456",
|
||||
# Rest is ignored
|
||||
"source": {
|
||||
"id": "card_18TY5wGGWE2Ias8Td38PjyPy",
|
||||
"object": "card",
|
||||
"address_city": None,
|
||||
"address_country": None,
|
||||
"address_line1": None,
|
||||
"address_line1_check": None,
|
||||
"address_line2": None,
|
||||
"address_state": None,
|
||||
"address_zip": None,
|
||||
"address_zip_check": None,
|
||||
"brand": "Visa",
|
||||
"country": "US",
|
||||
"customer": None,
|
||||
"cvc_check": "pass",
|
||||
"dynamic_last4": None,
|
||||
"exp_month": 12,
|
||||
"exp_year": 2016,
|
||||
"fingerprint": "FNbGTMaFvhRU2Y0E",
|
||||
"funding": "credit",
|
||||
"last4": "4242",
|
||||
"metadata": {},
|
||||
"name": "Carl Cardholder",
|
||||
"tokenization_method": None,
|
||||
},
|
||||
"payment_method": "pm_654321",
|
||||
"payment_method_details": {
|
||||
"card": {
|
||||
"amount_authorized": 3500,
|
||||
"authorization_code": "12345",
|
||||
"brand": "visa",
|
||||
"checks": {
|
||||
"address_line1_check": None,
|
||||
"address_postal_code_check": "pass",
|
||||
"cvc_check": "pass"
|
||||
},
|
||||
"country": "US",
|
||||
"exp_month": 12,
|
||||
"exp_year": 2034,
|
||||
"extended_authorization": {
|
||||
"status": "disabled"
|
||||
},
|
||||
"fingerprint": "ABCDE",
|
||||
"funding": "credit",
|
||||
"incremental_authorization": {
|
||||
"status": "unavailable"
|
||||
},
|
||||
"installments": None,
|
||||
"last4": "4242",
|
||||
"mandate": None,
|
||||
"multicapture": {
|
||||
"status": "unavailable"
|
||||
},
|
||||
"network": "visa",
|
||||
"network_token": {
|
||||
"used": False
|
||||
},
|
||||
"network_transaction_id": "12345",
|
||||
"overcapture": {
|
||||
"maximum_amount_capturable": 3500,
|
||||
"status": "unavailable"
|
||||
},
|
||||
"regulated_status": "unregulated",
|
||||
"three_d_secure": None,
|
||||
"transaction_link_id": None,
|
||||
"wallet": None
|
||||
},
|
||||
"type": "card"
|
||||
},
|
||||
"source": None,
|
||||
"source_transfer": None,
|
||||
"statement_descriptor": None,
|
||||
"status": "succeeded"
|
||||
}, None)
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@@ -231,7 +206,7 @@ def test_webhook_partial_refund(env, client, monkeypatch):
|
||||
payment = env[1].payments.create(
|
||||
provider='stripe', amount=env[1].total, info=json.dumps(charge)
|
||||
)
|
||||
ReferencedStripeObject.objects.create(order=env[1], reference="ch_18TY6GGGWE2Is8TZHanef25",
|
||||
ReferencedStripeObject.objects.create(order=env[1], reference="ch_18TY6GGGWE2Ias8TZHanef25",
|
||||
payment=payment)
|
||||
|
||||
charge['refunds'] = {
|
||||
@@ -242,7 +217,7 @@ def test_webhook_partial_refund(env, client, monkeypatch):
|
||||
"object": "refund",
|
||||
"amount": "12300",
|
||||
"balance_transaction": "txn_18otImGGWE2Ias8T4fLOxesC",
|
||||
"charge": "ch_18TY6GGGWE2Is8TZHanef25",
|
||||
"charge": "ch_18TY6GGGWE2Ias8TZHanef25",
|
||||
"created": 1472729052,
|
||||
"currency": "eur",
|
||||
"metadata": {},
|
||||
@@ -255,7 +230,7 @@ def test_webhook_partial_refund(env, client, monkeypatch):
|
||||
}
|
||||
monkeypatch.setattr("stripe.Charge.retrieve", lambda *args, **kwargs: charge)
|
||||
|
||||
r = client.post('/dummy/dummy/stripe/webhook/', json.dumps(
|
||||
client.post('/dummy/dummy/stripe/webhook/', json.dumps(
|
||||
{
|
||||
"id": "evt_18otImGGWE2Ias8TUyVRDB1G",
|
||||
"object": "event",
|
||||
@@ -263,9 +238,8 @@ def test_webhook_partial_refund(env, client, monkeypatch):
|
||||
"created": 1472729052,
|
||||
"data": {
|
||||
"object": {
|
||||
"id": "ch_18TY6GGGWE2Is8TZHanef25",
|
||||
"id": "ch_18TY6GGGWE2Ias8TZHanef25",
|
||||
"object": "charge",
|
||||
"payment_intent": "pi_123456",
|
||||
# Rest of object is ignored anway
|
||||
}
|
||||
},
|
||||
@@ -275,7 +249,6 @@ def test_webhook_partial_refund(env, client, monkeypatch):
|
||||
"type": "charge.refunded"
|
||||
}
|
||||
), content_type='application_json')
|
||||
print(r.content)
|
||||
|
||||
order = env[1]
|
||||
order.refresh_from_db()
|
||||
@@ -302,7 +275,7 @@ def test_webhook_global(env, client, monkeypatch):
|
||||
payment = order.payments.create(
|
||||
provider='stripe', amount=order.total, info=json.dumps(charge), state=OrderPayment.PAYMENT_STATE_CREATED
|
||||
)
|
||||
ReferencedStripeObject.objects.create(order=order, reference="ch_18TY6GGGWE2Is8TZHanef25",
|
||||
ReferencedStripeObject.objects.create(order=order, reference="ch_18TY6GGGWE2Ias8TZHanef25",
|
||||
payment=payment)
|
||||
ReferencedStripeObject.objects.create(order=order, reference="pi_123456",
|
||||
payment=payment)
|
||||
@@ -315,7 +288,7 @@ def test_webhook_global(env, client, monkeypatch):
|
||||
"created": 1472729052,
|
||||
"data": {
|
||||
"object": {
|
||||
"id": "ch_18TY6GGGWE2Is8TZHanef25",
|
||||
"id": "ch_18TY6GGGWE2Ias8TZHanef25",
|
||||
"object": "charge",
|
||||
"payment_intent": "pi_123456",
|
||||
"metadata": {
|
||||
@@ -333,3 +306,50 @@ def test_webhook_global(env, client, monkeypatch):
|
||||
|
||||
order.refresh_from_db()
|
||||
assert order.status == Order.STATUS_PAID
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_webhook_global_legacy_reference(env, client, monkeypatch):
|
||||
order = env[1]
|
||||
order.status = Order.STATUS_PENDING
|
||||
order.save()
|
||||
|
||||
charge = get_test_charge(env[1])
|
||||
charge["amount_refunded"] = 0
|
||||
monkeypatch.setattr("stripe.Charge.retrieve", lambda *args, **kwargs: charge)
|
||||
|
||||
with scopes_disabled():
|
||||
payment = order.payments.create(
|
||||
provider='stripe', amount=order.total, info=json.dumps(charge), state=OrderPayment.PAYMENT_STATE_CREATED
|
||||
)
|
||||
ReferencedStripeObject.objects.create(order=order, reference="ch_18TY6GGGWE2Ias8TZHanef25")
|
||||
ReferencedStripeObject.objects.create(order=order, reference="pi_123456")
|
||||
|
||||
client.post('/_stripe/webhook/', json.dumps(
|
||||
{
|
||||
"id": "evt_18otImGGWE2Ias8TUyVRDB1G",
|
||||
"object": "event",
|
||||
"api_version": "2016-03-07",
|
||||
"created": 1472729052,
|
||||
"data": {
|
||||
"object": {
|
||||
"id": "ch_18TY6GGGWE2Ias8TZHanef25",
|
||||
"object": "charge",
|
||||
"payment_intent": "pi_123456",
|
||||
"metadata": {
|
||||
"event": order.event_id,
|
||||
}
|
||||
# Rest of object is ignored anway
|
||||
}
|
||||
},
|
||||
"livemode": True,
|
||||
"pending_webhooks": 1,
|
||||
"request": "req_977XOWC8zk51Z9",
|
||||
"type": "charge.succeeded"
|
||||
}
|
||||
), content_type='application_json')
|
||||
|
||||
order.refresh_from_db()
|
||||
assert order.status == Order.STATUS_PAID
|
||||
with scopes_disabled():
|
||||
assert list(order.payments.all()) == [payment]
|
||||
@@ -30,7 +30,10 @@ from urllib.parse import quote
|
||||
import jwt
|
||||
import pytest
|
||||
from bs4 import BeautifulSoup
|
||||
from Crypto.PublicKey import RSA
|
||||
from cryptography.hazmat.primitives.asymmetric.rsa import (
|
||||
RSAPublicKey, RSAPublicNumbers,
|
||||
)
|
||||
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
|
||||
from django.utils.timezone import now
|
||||
from django_scopes import scopes_disabled
|
||||
from freezegun import freeze_time
|
||||
@@ -691,6 +694,11 @@ def test_keys_endpoint(env, client, ssoclient):
|
||||
|
||||
e = decode_int(data['keys'][0]['e'])
|
||||
n = decode_int(data['keys'][0]['n'])
|
||||
pubkey = RSA.construct((n, e))
|
||||
representation = pubkey.export_key('PEM').decode()
|
||||
pubkey = RSAPublicNumbers(e, n).public_key()
|
||||
assert isinstance(pubkey, RSAPublicKey)
|
||||
|
||||
representation = pubkey.public_bytes(
|
||||
Encoding.PEM, PublicFormat.SubjectPublicKeyInfo
|
||||
).decode()
|
||||
|
||||
assert representation.strip() == env[0].settings.sso_server_signing_key_rsa256_public.strip()
|
||||
@@ -1791,13 +1791,15 @@ class OrdersTest(BaseOrdersTest):
|
||||
assert match
|
||||
|
||||
response = self.client.get(
|
||||
'/%s/%s/answer/%s/?token=%s' % (self.orga.slug, self.event.slug, a.pk, match.group(1))
|
||||
'/%s/%s/order/%s/%s/answer/%s/?token=%s' % (self.orga.slug, self.event.slug, self.order.code,
|
||||
self.order.secret, a.pk, match.group(1))
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
client2 = self.client_class()
|
||||
response = client2.get(
|
||||
'/%s/%s/answer/%s/?token=%s' % (self.orga.slug, self.event.slug, a.pk, match.group(1))
|
||||
'/%s/%s/order/%s/%s/answer/%s/?token=%s' % (self.orga.slug, self.event.slug, self.order.code,
|
||||
self.order.secret, a.pk, match.group(1))
|
||||
)
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
+1
-3
@@ -7,9 +7,7 @@
|
||||
],
|
||||
"compilerOptions": {
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["./src/*"],
|
||||
},
|
||||
"paths": {},
|
||||
"strict": false,
|
||||
"allowJs": true,
|
||||
"checkJs": true,
|
||||
|
||||
+3
-6
@@ -25,9 +25,6 @@ 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: {
|
||||
@@ -40,12 +37,12 @@ export default defineConfig({
|
||||
},
|
||||
build: {
|
||||
manifest: true,
|
||||
outDir: path.resolve(import.meta.dirname, 'src/pretix/static.dist/vite/control'),
|
||||
outDir: path.resolve(__dirname, 'src/pretix/static.dist/vite/control'),
|
||||
rollupOptions: {
|
||||
preserveEntrySignatures: 'exports-only',
|
||||
input: {
|
||||
'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'),
|
||||
'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'),
|
||||
...Object.fromEntries(SHARED_DEPS.map(dep => [`_vendor/${dep}`, `virtual:vendor/${dep}`])),
|
||||
...pretixPluginEntries,
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user