Compare commits

..
Author SHA1 Message Date
Kara Engelhardt 9520c411db Format js code with prettier 2026-11-13 16:41:15 +01:00
Kara Engelhardt 749211c206 Add prettier config 2026-11-13 16:41:15 +01:00
119 changed files with 4160 additions and 3910 deletions

No files matched your search

+1 -1
View File
@@ -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
-1
View File
@@ -1 +0,0 @@
/*
+5 -17
View File
@@ -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": {}
}
]
}
+1 -1
View File
@@ -1,6 +1,6 @@
sphinx==9.0.*
sphinx-rtd-theme~=3.1.0
sphinxcontrib-httpdomain~=2.2.1
sphinxcontrib-httpdomain~=2.1.0
sphinxcontrib-images~=1.0.1
sphinxcontrib-jquery~=4.1
sphinxcontrib-spelling~=8.0.2
+1 -1
View File
@@ -1,7 +1,7 @@
-e ../
sphinx==9.0.*
sphinx-rtd-theme~=3.1.0
sphinxcontrib-httpdomain~=2.2.1
sphinxcontrib-httpdomain~=2.1.0
sphinxcontrib-images~=1.0.1
sphinxcontrib-jquery~=4.1
sphinxcontrib-spelling~=8.0.2
+2
View File
@@ -5,6 +5,7 @@ import ts from 'typescript-eslint'
import stylistic from '@stylistic/eslint-plugin'
import vue from 'eslint-plugin-vue'
import vuePug from 'eslint-plugin-vue-pug'
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';
const ignores = globalIgnores([
'**/node_modules',
@@ -161,4 +162,5 @@ export default defineConfig([
},
},
},
eslintPluginPrettierRecommended,
])
+127
View File
@@ -21,9 +21,12 @@
"@vue/eslint-config-typescript": "^14.7.0",
"@vue/language-plugin-pug": "^3.2.5",
"eslint": "^10.0.3",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.5.7",
"eslint-plugin-vue": "^10.8.0",
"eslint-plugin-vue-pug": "^1.0.0-alpha.5",
"globals": "^17.4.0",
"prettier": "3.10.1",
"pug": "^3.0.3",
"sass-embedded": "^1.98.0",
"smol-toml": "^1.6.1",
@@ -92,6 +95,17 @@
"dev": true,
"license": "(Apache-2.0 AND BSD-3-Clause)"
},
"node_modules/@dual-bundle/import-meta-resolve": {
"version": "4.2.1",
"resolved": "https://registry.npmjs.org/@dual-bundle/import-meta-resolve/-/import-meta-resolve-4.2.1.tgz",
"integrity": "sha512-id+7YRUgoUX6CgV0DtuhirQWodeeA7Lf4i2x71JS/vtA5pRb/hIGWlw+G6MeXvsM+MXrz0VAydTGElX1rAfgPg==",
"dev": true,
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/JounQin"
}
},
"node_modules/@eslint-community/eslint-utils": {
"version": "4.9.1",
"resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz",
@@ -718,6 +732,19 @@
"node": ">=14"
}
},
"node_modules/@pkgr/core": {
"version": "0.3.6",
"resolved": "https://registry.npmjs.org/@pkgr/core/-/core-0.3.6.tgz",
"integrity": "sha512-SEeaJLb3qBNF/OaXnaR1NmmBbFYk1zC0ZH/52fATcRPLFg/p791YrcyFFy44Bo9sLaGuSuLp5Q6axbb/O+v/RA==",
"dev": true,
"license": "MIT",
"engines": {
"node": "^14.18.0 || >=16.0.0"
},
"funding": {
"url": "https://opencollective.com/pkgr"
}
},
"node_modules/@rolldown/binding-android-arm-eabi": {
"version": "1.2.15",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.15.tgz",
@@ -1966,6 +1993,53 @@
}
}
},
"node_modules/eslint-config-prettier": {
"version": "10.1.8",
"resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-10.1.8.tgz",
"integrity": "sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w==",
"dev": true,
"license": "MIT",
"bin": {
"eslint-config-prettier": "bin/cli.js"
},
"funding": {
"url": "https://opencollective.com/eslint-config-prettier"
},
"peerDependencies": {
"eslint": ">=7.0.0"
}
},
"node_modules/eslint-plugin-prettier": {
"version": "5.5.7",
"resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-5.5.7.tgz",
"integrity": "sha512-WjHyn3GrFd+ZR0rzsLiM4zJZ35PZMOE0SUIxzGmnWNG0126yNfJKJzObmmkYDwHJfGlkz3PSlzyG9ez/LJntwg==",
"dev": true,
"license": "MIT",
"dependencies": {
"prettier-linter-helpers": "^1.0.1",
"synckit": "^0.12.3"
},
"engines": {
"node": "^14.18.0 || >=16.0.0"
},
"funding": {
"url": "https://opencollective.com/eslint-plugin-prettier"
},
"peerDependencies": {
"@types/eslint": ">=8.0.0",
"eslint": ">=8.0.0",
"eslint-config-prettier": ">= 7.0.0 <10.0.0 || >=10.1.0",
"prettier": ">=3.0.0"
},
"peerDependenciesMeta": {
"@types/eslint": {
"optional": true
},
"eslint-config-prettier": {
"optional": true
}
}
},
"node_modules/eslint-plugin-vue": {
"version": "10.8.0",
"resolved": "https://registry.npmjs.org/eslint-plugin-vue/-/eslint-plugin-vue-10.8.0.tgz",
@@ -2190,6 +2264,13 @@
"dev": true,
"license": "MIT"
},
"node_modules/fast-diff": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/fast-diff/-/fast-diff-1.3.0.tgz",
"integrity": "sha512-VxPP4NqbUjj6MaAOafWeUn2cXWLcCtljklUtZf0Ind4XQ+QPtmA0b18zZy0jIQx+ExRVCR/ZQpBmik5lXshNsw==",
"dev": true,
"license": "Apache-2.0"
},
"node_modules/fast-glob": {
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz",
@@ -3361,6 +3442,35 @@
"node": ">= 0.8.0"
}
},
"node_modules/prettier": {
"version": "3.10.1",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.10.1.tgz",
"integrity": "sha512-70vp3ZUYoPlFbF9uiTdXHUUCGEIp7d4+6p+8DYbkm2jP7x/3i/paXVF6dopSI3zd/CEitrZN1rc4i85xWmmXlg==",
"dev": true,
"license": "MIT",
"bin": {
"prettier": "bin/prettier.cjs"
},
"engines": {
"node": ">=14"
},
"funding": {
"url": "https://github.com/prettier/prettier?sponsor=1"
}
},
"node_modules/prettier-linter-helpers": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/prettier-linter-helpers/-/prettier-linter-helpers-1.0.1.tgz",
"integrity": "sha512-SxToR7P8Y2lWmv/kTzVLC1t/GDI2WGjMwNhLLE9qtH8Q13C+aEmuRlzDst4Up4s0Wc8sF2M+J57iB3cMLqftfg==",
"dev": true,
"license": "MIT",
"dependencies": {
"fast-diff": "^1.1.2"
},
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/promise": {
"version": "7.3.1",
"resolved": "https://registry.npmjs.org/promise/-/promise-7.3.1.tgz",
@@ -4300,6 +4410,23 @@
"node": ">=16.0.0"
}
},
"node_modules/synckit": {
"version": "0.12.3",
"resolved": "https://registry.npmjs.org/synckit/-/synckit-0.12.3.tgz",
"integrity": "sha512-U+/AXT6LWsxnj2vz9HeUuPWBNgdWxjyIEjEPdbJARC9txmgPzo2VEdqnFo4hHaNyMPtycyVJrSaQYeQv/PoyyA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@dual-bundle/import-meta-resolve": "^4.2.1",
"@pkgr/core": "^0.3.6"
},
"engines": {
"node": "^14.18.0 || >=16.0.0"
},
"funding": {
"url": "https://opencollective.com/synckit"
}
},
"node_modules/tinyglobby": {
"version": "0.2.17",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
+3
View File
@@ -39,9 +39,12 @@
"@vue/eslint-config-typescript": "^14.7.0",
"@vue/language-plugin-pug": "^3.2.5",
"eslint": "^10.0.3",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.5.7",
"eslint-plugin-vue": "^10.8.0",
"eslint-plugin-vue-pug": "^1.0.0-alpha.5",
"globals": "^17.4.0",
"prettier": "3.10.1",
"pug": "^3.0.3",
"sass-embedded": "^1.98.0",
"smol-toml": "^1.6.1",
+5 -6
View File
@@ -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",
@@ -81,7 +81,7 @@ dependencies = [
"pycountry",
"pycparser==3.12",
"pycryptodome==3.24.*",
"pypdf==6.21.*",
"pypdf==6.20.*",
"python-bidi==0.6.*", # Support for Arabic in reportlab
"python-dateutil==4.0.*",
"pytz",
@@ -91,7 +91,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 +123,7 @@ dev = [
"pytest-sugar",
"pytest-xdist==3.8.*",
"pytest-playwright",
"pytest-base-url",
"pytest==9.2.*",
"pytest==9.1.*",
"playwright",
"responses",
"pypdfium2"
+1
View File
@@ -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'),
)
-8
View File
@@ -156,8 +156,6 @@ class ExportFormDataField(serializers.Field):
return JobRunSerializer(exporter=exporter).to_internal_value(data["export_form_data"])
else:
return data['export_form_data']
else: # partial PATCH without export_form_data keeps it unchanged
return self.parent.instance.export_form_data
class ScheduledExportSerializer(serializers.ModelSerializer):
@@ -190,12 +188,6 @@ class ScheduledExportSerializer(serializers.ModelSerializer):
raise ValidationError('Please enter less than 25 recipients.')
return d
def validate(self, attrs):
attrs = super().validate(attrs)
if self.instance and self.instance.pk and 'export_identifier' in attrs and self.instance.export_identifier != attrs['export_identifier']:
raise ValidationError({"export_identifier": "export_identifier cannot be changed for existing exports."})
return attrs
class ScheduledEventExportSerializer(ScheduledExportSerializer):
+2 -3
View File
@@ -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):
+33 -47
View File
@@ -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):
@@ -274,8 +272,6 @@ class ScheduledEventExportViewSet(ScheduledExportersViewSet):
perm_holder = self.request.auth if isinstance(self.request.auth, (TeamAPIToken, Device)) else self.request.user
if not perm_holder.has_event_permission(self.request.organizer, self.request.event, exporter.get_required_event_permission()):
raise PermissionDenied("No permission to edit exports you could not run.")
# An additional check for the new config, such as on organizer level, is not necessary. Since the event is
# fixed and the export_identifier is read-only, the update cannot include a meaningful change of permissions.
serializer.save(event=self.request.event)
serializer.instance.compute_next_run()
@@ -348,41 +344,6 @@ class ScheduledOrganizerExportViewSet(ScheduledExportersViewSet):
))
return {e.identifier: e for e in exporters}
def _check_permission_for_export(self, identifier, form_data):
perm_holder = (
self.request.auth if isinstance(self.request.auth, (Device, TeamAPIToken)) else self.request.user
)
exporter = self.exporters.get(identifier)
if not exporter:
raise PermissionDenied("No access to exporter.")
if isinstance(exporter, OrganizerLevelExportMixin):
if not perm_holder.has_organizer_permission(
self.request.organizer, exporter.get_required_organizer_permission(), request=self.request,
):
raise PermissionDenied("No permission to edit exports you could not run.")
else:
if form_data.get("all_events", False):
if isinstance(self.request.auth, Device):
if not self.request.auth.all_events:
raise PermissionDenied("No permission to edit exports you could not run.")
elif isinstance(self.request.auth, TeamAPIToken):
if not self.request.auth.team.all_events:
raise PermissionDenied("No permission to edit exports you could not run.")
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.")
else:
events_selected = form_data.get("events", [])
events_permission = set(perm_holder.get_events_with_permission(
exporter.get_required_event_permission(), request=self.request
).values_list("pk", flat=True))
if not all(e in events_permission for e in events_selected):
raise PermissionDenied("No permission to edit exports you could not run.")
@transaction.atomic()
def perform_update(self, serializer):
if not self.request.user.is_authenticated or self.request.user != serializer.instance.owner:
@@ -390,12 +351,37 @@ class ScheduledOrganizerExportViewSet(ScheduledExportersViewSet):
# user B has settings permission (= they can see the export configuration), but not enough permission
# to run the export themselves. Without this check, user B could modify the export and add themselves
# as a recipient. Thereby, user B would gain access to data they can't have.
self._check_permission_for_export(serializer.instance.export_identifier, serializer.instance.export_form_data)
# After we checked that the API user can work with the original export, we also need to check that they can
# work with the changed export, otherwise they could change e.g. from "some events" to "all events" and add
# themselves as a recipient.
if serializer.validated_data.get('export_form_data') is not None:
self._check_permission_for_export(serializer.instance.export_identifier, serializer.validated_data['export_form_data'])
exporter = self.exporters.get(serializer.instance.export_identifier)
if not exporter:
raise PermissionDenied("No access to exporter.")
perm_holder = (self.request.auth if isinstance(self.request.auth, (Device, TeamAPIToken))
else self.request.user)
if isinstance(exporter, OrganizerLevelExportMixin):
if not perm_holder.has_organizer_permission(
self.request.organizer, exporter.get_required_organizer_permission(), request=self.request,
):
raise PermissionDenied("No permission to edit exports you could not run.")
else:
if serializer.instance.export_form_data.get("all_events", False):
if isinstance(self.request.auth, Device):
if not self.request.auth.all_events:
raise PermissionDenied("No permission to edit exports you could not run.")
elif isinstance(self.request.auth, TeamAPIToken):
if not self.request.auth.team.all_events:
raise PermissionDenied("No permission to edit exports you could not run.")
elif self.request.user.is_authenticated:
if not self.request.user.teams.filter(
TeamQuerySet.event_permission_q(exporter.get_required_event_permission()),
all_events=True,
).exists():
raise PermissionDenied("No permission to edit exports you could not run.")
else:
events_selected = serializer.instance.export_form_data.get("events", [])
events_permission = set(perm_holder.get_events_with_permission(
exporter.get_required_event_permission(), request=self.request
).values_list("pk", flat=True))
if not all(e in events_permission for e in events_selected):
raise PermissionDenied("No permission to edit exports you could not run.")
serializer.save(organizer=self.request.organizer)
serializer.instance.compute_next_run()
+12 -16
View File
@@ -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']
+1 -3
View File
@@ -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
+47
View File
@@ -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
+1 -1
View File
@@ -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:
+4 -6
View File
@@ -1343,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
@@ -1488,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):
@@ -1570,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):
+21 -2
View File
@@ -93,7 +93,7 @@ from ...testutils.middleware import debugflags_var
from ._transactions import (
_fail, _transactions_mark_order_clean, _transactions_mark_order_dirty,
)
from .base import 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)
-1
View File
@@ -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(
+15 -43
View File
@@ -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)
-17
View File
@@ -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 ""
+2 -16
View File
@@ -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)
-11
View File
@@ -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'):
+2 -2
View File
@@ -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:
@@ -23,7 +23,6 @@
<link rel="manifest" href="{% url "site.webmanifest" %}">
<link rel="mask-icon" href="{% static "pretixbase/img/icons/safari-pinned-tab.svg" %}" color="#3b1c4a">
<meta name="theme-color" content="#3b1c4a">
<script type="text/javascript" src="{% static "pretixbase/js/csrfcookieretry.js" %}"></script>
</head>
<body>
<div class="container">
@@ -44,7 +44,7 @@
{% endblocktrans %}
</div>
{% endif %}
{% if not request.event.has_subevents and object.hidden_if_item_available and object.hidden_if_item_available.check_quotas.0 == 100 and object.hidden_if_item_available.is_available %}
{% if not request.event.has_subevents and object.hidden_if_item_available and object.hidden_if_item_available.check_quotas.0 == 100 %}
<div class="alert alert-warning">
{% blocktrans trimmed %}
This product is currently not being shown since you configured below that it should only be visible
@@ -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 %}
-1
View File
@@ -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
+4 -12
View File
@@ -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():
+6 -25
View File
@@ -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):
@@ -2128,7 +2124,7 @@ class ExportView(OrganizerPermissionRequiredMixin, ExportMixin, ListView):
@transaction.atomic()
def post(self, request, *args, **kwargs):
if request.POST.get("schedule") == "save":
if self.scheduled and self.scheduled.pk and not self.has_permission_to_edit_scheduled(self.scheduled.export_form_data):
if self.scheduled and self.scheduled.pk and not self.has_permission_to_edit_scheduled():
messages.error(
self.request,
_(
@@ -2147,16 +2143,6 @@ class ExportView(OrganizerPermissionRequiredMixin, ExportMixin, ListView):
)
return super().get(request, *args, **kwargs)
elif self.exporter.form.is_valid() and self.rrule_form.is_valid() and self.schedule_form.is_valid():
if self.scheduled and self.scheduled.pk and not self.has_permission_to_edit_scheduled(self.exporter.form.cleaned_data):
messages.error(
self.request,
_(
"This report runs with the permissions of a different user and you do not have access to all "
"events, therefore you cannot change it to cover additional events."
)
)
return super().get(request, *args, **kwargs)
self.schedule_form.instance.export_identifier = self.exporter.identifier
self.schedule_form.instance.export_form_data = self.exporter.form.cleaned_data
self.schedule_form.instance.schedule_rrule = str(self.rrule_form.to_rrule())
@@ -2210,10 +2196,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,
@@ -2242,7 +2224,7 @@ class ExportView(OrganizerPermissionRequiredMixin, ExportMixin, ListView):
def get_queryset(self):
return self.get_scheduled_queryset()
def has_permission_to_edit_scheduled(self, export_form_data):
def has_permission_to_edit_scheduled(self):
# Exports can be edited by
# - their owner
# - any staff session user
@@ -2267,16 +2249,15 @@ class ExportView(OrganizerPermissionRequiredMixin, ExportMixin, ListView):
self.request.organizer, self.exporter.get_required_organizer_permission(), request=self.request
)
else:
if export_form_data.get("all_events", False):
if self.scheduled.export_form_data.get("all_events", False):
# 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:
# Test scenario 3/4 in test_organizer_edit_restrictions
events_selected = export_form_data.get("events", [])
events_selected = self.scheduled.export_form_data.get("events", [])
events_permission = set(self.request.user.get_events_with_permission(
self.exporter.get_required_event_permission(), request=self.request,
).values_list("pk", flat=True))
@@ -2304,7 +2285,7 @@ class ExportView(OrganizerPermissionRequiredMixin, ExportMixin, ListView):
ctx['rrule_form'] = self.rrule_form
ctx['scheduled_copy_from'] = self.scheduled_copy_from
if self.scheduled and self.scheduled.pk and not self.has_permission_to_edit_scheduled(self.scheduled.export_form_data) and self.exporter:
if self.scheduled and self.scheduled.pk and not self.has_permission_to_edit_scheduled() and self.exporter:
ctx['no_save'] = True
for f in self.exporter.form.fields.values():
f.disabled = True
-6
View File
@@ -1520,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']:
@@ -1559,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
-29
View File
@@ -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)
-22
View File
@@ -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()
+2 -2
View File
@@ -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)
+7 -6
View File
@@ -5,7 +5,7 @@ msgstr ""
"Project-Id-Version: 1\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-10-28 10:48+0000\n"
"PO-Revision-Date: 2026-11-06 22:00+0000\n"
"PO-Revision-Date: 2026-10-28 11:13+0000\n"
"Last-Translator: Raphael Michel <michel@rami.io>\n"
"Language-Team: German <https://translate.pretix.eu/projects/pretix/pretix/"
"de/>\n"
@@ -14,7 +14,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.1\n"
"X-Generator: Weblate 2026.10.1\n"
"X-Poedit-Bookmarks: -1,-1,904,-1,-1,-1,-1,-1,-1,-1\n"
#: pretix/_base_settings.py
@@ -12572,16 +12572,17 @@ msgid ""
msgstr ""
"Hallo {name},\n"
"\n"
"Sie haben angefragt, Ihre E-Mail-Adresse für Ihr Kundenkonto bei {organizer} "
"zu ändern.\n"
"vielen Dank für Ihre Anmeldung für ein Kundenkonto bei {organizer}!\n"
"\n"
"Um dies zu bestätigen, klicken Sie bitte hier:\n"
"Um Ihr Kundenkonto zu aktivieren und ein Passwort zu wählen, klicken Sie "
"bitte hier:\n"
"\n"
"{url}\n"
"\n"
"Dieser Link ist gültig für einen Tag.\n"
"\n"
"Wenn Sie dies nicht angefragt haben, können Sie diese E-Mail ignorieren.\n"
"Wenn Sie sich nicht selbst angemeldet haben, können Sie diese E-Mail "
"ignorieren.\n"
"\n"
"Viele Grüße\n"
"\n"
@@ -8,7 +8,7 @@ msgstr ""
"Project-Id-Version: 1\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-10-28 10:48+0000\n"
"PO-Revision-Date: 2026-11-06 22:00+0000\n"
"PO-Revision-Date: 2026-10-28 11:13+0000\n"
"Last-Translator: Raphael Michel <michel@rami.io>\n"
"Language-Team: German (informal) <https://translate.pretix.eu/projects/"
"pretix/pretix/de_Informal/>\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.1\n"
"X-Generator: Weblate 2026.10.1\n"
#: pretix/_base_settings.py
msgid "English"
@@ -12552,16 +12552,17 @@ msgid ""
msgstr ""
"Hallo {name},\n"
"\n"
"du hast angefragt, die E-Mail-Adresse für dein Kundenkonto bei {organizer} "
"zu ändern.\n"
"vielen Dank für deine Anmeldung für ein Kundenkonto bei {organizer}!\n"
"\n"
"Um die Änderung zu bestätigen, klicke bitte hier:\n"
"Um dein Kundenkonto zu aktivieren und ein Passwort zu wählen, klicke bitte "
"hier:\n"
"\n"
"{url}\n"
"\n"
"Dieser Link ist gültig für einen Tag.\n"
"\n"
"Wenn du dies nicht angefordert hast, kannst du diese E-Mail ignorieren.\n"
"Wenn du dich nicht selbst angemeldet hast, kannst du diese E-Mail "
"ignorieren.\n"
"\n"
"Viele Grüße\n"
"\n"
+4 -4
View File
@@ -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}"
+52 -114
View File
@@ -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-15 23:00+0000\n"
"Last-Translator: Ikuisuus <kkujala@paivola.fi>\n"
"PO-Revision-Date: 2025-10-04 10:10+0000\n"
"Last-Translator: Sebastian Bożek <sebastian@log-mar.pl>\n"
"Language-Team: Finnish <https://translate.pretix.eu/projects/pretix/pretix/"
"fi/>\n"
"Language: fi\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 5.13.3\n"
#: pretix/_base_settings.py
msgid "English"
@@ -57,7 +57,7 @@ msgstr "tšekki"
#: pretix/_base_settings.py
msgid "Croatian"
msgstr "kroatia"
msgstr "Kroatia"
#: pretix/_base_settings.py
msgid "Danish"
@@ -89,11 +89,11 @@ msgstr "kreikka"
#: pretix/_base_settings.py
msgid "Hebrew"
msgstr "Heprea"
msgstr ""
#: pretix/_base_settings.py
msgid "Hungarian"
msgstr "Unkari"
msgstr ""
#: pretix/_base_settings.py
msgid "Indonesian"
@@ -149,11 +149,11 @@ msgstr "espanja"
#: pretix/_base_settings.py
msgid "Spanish (Latin America)"
msgstr "Espanja (Etelä-Afrikka)"
msgstr ""
#: pretix/_base_settings.py
msgid "Thai"
msgstr "Thai"
msgstr ""
#: pretix/_base_settings.py
msgid "Turkish"
@@ -297,16 +297,22 @@ msgid "The bundled item must not have bundles on its own."
msgstr "Niputettavalla tuotteella ei saa olla nippuja."
#: pretix/api/serializers/item.py
#, fuzzy
#| msgid "The payment is too late to be accepted."
msgid "The program start must not be empty."
msgstr "Ohjelman alku ei voi olla tyhjä."
msgstr "Maksu on liian myöhässä hyväksyttäväksi."
#: pretix/api/serializers/item.py
#, fuzzy
#| msgid "The payment is too late to be accepted."
msgid "The program end must not be empty."
msgstr "Ohjelman loppu ei saa olla tyhjä."
msgstr "Maksu on liian myöhässä hyväksyttäväksi."
#: pretix/api/serializers/item.py pretix/base/models/items.py
#, fuzzy
#| msgid "The maximum count needs to be greater than the minimum count."
msgid "The program end must not be before the program start."
msgstr "Ohjelma ei voi päättyä ennen kuin se alkaa."
msgstr "Enimmäismäärän on oltava suurempi kuin vähimmäismäärä."
#: pretix/api/serializers/item.py pretix/base/models/items.py
#, fuzzy
@@ -614,8 +620,6 @@ msgid ""
"This includes related events like creation, deletion, opening or closing of "
"quotas. No webhook is sent for changes to the resulting availability."
msgstr ""
"Tämä sisältää toiminnot kuten luonti, poisto, kiintiöiden avaamiset tai "
"sulkemiset. Aiheutuneista muutoksista ei lähetetä Webhook pyyntöä."
#: pretix/api/webhooks.py
msgid "Shop taken live"
@@ -666,8 +670,6 @@ msgid ""
"Only includes explicit changes to the voucher, not e.g. an increase of the "
"number of redemptions."
msgstr ""
"Sisältää vain varsinaiset muutokset kuponkiin, ei esimerkiksi lisäyksiä "
"lunastuskertoihin."
#: pretix/api/webhooks.py
#, fuzzy
@@ -848,7 +850,6 @@ msgid ""
"Field \"{field_name}\" does not exist. Please check your {provider_name} "
"settings."
msgstr ""
"Kenttä {field_name} ei ole olemassa. Tarkista {provider_name} asetukset."
#: pretix/base/datasync/datasync.py
#, python-brace-format
@@ -856,8 +857,6 @@ msgid ""
"Field \"{field_name}\" requires {required_input}, but only got "
"{available_inputs}. Please check your {provider_name} settings."
msgstr ""
"Kenttä {field_name} vaatii {required_input}, mutta sai vain "
"{available_inputs}. Tarkista {provider_name} asetukset."
#: pretix/base/datasync/datasync.py
#, python-brace-format
@@ -865,8 +864,6 @@ msgid ""
"Please update value mapping for field \"{field_name}\" - option \"{val}\" "
"not assigned"
msgstr ""
"Päivitä arvot kenttään {field_name} - vaihtoehdon {val} arvoa ei ole "
"määritetty"
#: pretix/base/datasync/sourcefields.py
#, fuzzy
@@ -897,7 +894,7 @@ msgstr "Tuotetiedot"
#: pretix/control/templates/pretixcontrol/order/index.html
#: pretix/presale/templates/pretixpresale/event/order.html
msgid "Order details"
msgstr "Tilauksen yksityiskohdat"
msgstr ""
#: pretix/base/datasync/sourcefields.py pretix/base/modelimport_orders.py
#: pretix/control/forms/filter.py
@@ -1307,7 +1304,7 @@ msgstr "Asiakkaat"
#: pretix/presale/templates/pretixpresale/organizers/customer_memberships.html
#: pretix/presale/views/customer.py
msgid "Memberships"
msgstr "Jäsenyydet"
msgstr ""
#: pretix/base/exporters/customers.py pretix/base/models/customers.py
#: pretix/control/templates/pretixcontrol/organizers/customer.html
@@ -2228,10 +2225,6 @@ msgid ""
"contain at least one position of this product. The order totals etc. still "
"include all products contained in the order."
msgstr ""
"Mikäli mitään ei valita, kaikki tuotteet sisällytetään. Tilaukset "
"sisältyvät, mikäli niissä on edes yksi valittu tuote. Tilauksen kokonaisarvo "
"ja muut vastaavat. yhä sisältävät kaikki tuotteet, jotka sisältyivät tähän "
"tilaukseen."
#: pretix/base/exporters/orderlist.py pretix/base/exporters/waitinglist.py
#: pretix/control/forms/event.py pretix/control/forms/organizer.py
@@ -3103,7 +3096,7 @@ msgstr "Sähköpostiosoite"
#: pretix/base/forms/auth.py pretix/control/forms/orders.py
#: pretix/control/templates/pretixcontrol/shredder/download.html
msgid "Confirmation code"
msgstr "Varmistuskoodi"
msgstr ""
#: pretix/base/forms/questions.py
#, fuzzy
@@ -3123,12 +3116,11 @@ msgid ""
"The field \"%(label)s\" may not contain special characters such as "
"\"%(chars)s\"."
msgstr ""
"Kenttä \"%(label)s\" ei saisi sisältää erikoismerkkejä kuten \"%(chars)s\"."
#: pretix/base/forms/questions.py
#, python-format
msgid "The field \"%(label)s\" may not contain an URL (%(url)s)."
msgstr "Kenttä \"%(label)s\" ei saisi sisältää URL-osoitetta %(url)s."
msgstr ""
#: pretix/base/forms/questions.py
msgctxt "phonenumber"
@@ -3194,7 +3186,7 @@ msgstr "Syötä lyhyempi nimi."
#: pretix/base/forms/questions.py
#, python-brace-format
msgid "Please enter a date and time between {min} and {max}."
msgstr "Syötä päivämäärä ja aika väliltä {min} ja {max}."
msgstr ""
#: pretix/base/forms/questions.py
#, fuzzy, python-brace-format
@@ -3417,7 +3409,7 @@ msgstr "Sähköpostiosoite vahvistettu"
#: pretix/base/invoicing/email.py
msgid "PDF via email"
msgstr "PDF sähköpostilla"
msgstr ""
#: pretix/base/invoicing/national.py
msgctxt "italian_invoice"
@@ -3859,7 +3851,7 @@ msgstr "Löytyi useita vastaavia päivämääriä."
#: pretix/base/modelimport_orders.py
msgid "Grouping"
msgstr "Ryhmittely"
msgstr ""
#: pretix/base/modelimport_orders.py
msgid ""
@@ -3878,9 +3870,6 @@ msgid ""
"The date can be specified through its full name, full date and time, or "
"internal ID, provided only one date in the system matches the input."
msgstr ""
"Päivään voi viitata sen koko nimellä, täydellä päivämääräällä ja ajalla tai "
"sisäisellä ID:llä, kunhan vain yksi päivämäärä järjestelmässä vastaa "
"syötteeseen."
#: pretix/base/modelimport_orders.py pretix/presale/views/waiting.py
msgctxt "subevent"
@@ -3891,8 +3880,6 @@ msgstr "Sinun täytyy valita päivämäärä."
msgid ""
"The product can be specified by its internal ID, full name or internal name."
msgstr ""
"Tuotteen voi tunnistaa sen sisäisellä ID:llä, koko nimellä tai sisäisellä "
"nimellä."
#: pretix/base/modelimport_orders.py pretix/base/modelimport_vouchers.py
msgid "No matching product was found."
@@ -3910,7 +3897,7 @@ msgstr "Tuotevariaatio"
#: pretix/base/modelimport_orders.py
msgid "The variation can be specified by its internal ID or full name."
msgstr "Variaatioon voi viitata sen sisäisellä ID:llä tai koko nimellä."
msgstr ""
#: pretix/base/modelimport_orders.py pretix/base/modelimport_vouchers.py
msgid "No matching variation was found."
@@ -3936,7 +3923,7 @@ msgstr "Syötä kelvollinen maatunnus."
#: pretix/base/modelimport_orders.py
msgid "The state can be specified by its short form or full name."
msgstr "Tilaan voi viitata sen lyhyellä muodolla tai koko nimellä."
msgstr ""
#: pretix/base/modelimport_orders.py
msgid "States are not supported for this country."
@@ -3982,7 +3969,7 @@ msgstr "Syötä kelvollinen kielikoodi."
msgid ""
"The sales channel can be specified by it's internal identifier or its full "
"name."
msgstr "Myyntikanavaan voi viitata sen sisäisellä ID:llä tai koko nimellä."
msgstr ""
#: pretix/base/modelimport_orders.py
msgid "Please enter a valid sales channel."
@@ -3990,7 +3977,7 @@ msgstr "Syötä kelvollinen myyntikanava."
#: pretix/base/modelimport_orders.py
msgid "The seat needs to be specified by its internal ID."
msgstr "Paikkaan täytyy viitata sen sisäisellä ID:llä."
msgstr ""
#: pretix/base/modelimport_orders.py pretix/base/modelimport_vouchers.py
msgid "Multiple matching seats were found."
@@ -4494,7 +4481,6 @@ msgstr "Erota useat arvot välilyönneillä"
#: pretix/base/models/datasync.py
msgid "Temporary error, auto-retry limit exceeded"
msgstr ""
"Väliaikainen virhe, automattisten uudelleen yritysten limiitti on ylitetty"
#: pretix/base/models/datasync.py
#, fuzzy
@@ -4508,7 +4494,7 @@ msgstr ""
#: pretix/base/models/datasync.py
msgid "System error, needs manual intervention"
msgstr "Systeemivirhe, vattii manuaalista korjaamista"
msgstr ""
#: pretix/base/models/devices.py pretix/base/models/items.py
msgid "Internal identifier"
@@ -4773,15 +4759,13 @@ msgstr "Valinnainen. Tuotteita ei myydä ennen tätä."
#: pretix/base/models/event.py
msgid "This event is remote or partially remote."
msgstr "Tämä tapahtuma järjestetään joko osittain tai kokonaan etänä."
msgstr ""
#: pretix/base/models/event.py
msgid ""
"This will be used to let users know if the event is in a different timezone, "
"and to let us calculate the local time of a user."
msgstr ""
"Tätä käytetään kertoakseen käyttäjille jos tapahtuma on eri aikavyöhykkeellä "
"ja mahdollistetaan käyttäjän paikallisen ajankohdan laskeminen."
#: pretix/base/models/event.py pretix/base/models/organizer.py
#: pretix/control/navigation.py
@@ -5077,7 +5061,7 @@ msgstr "Puuttuva summa"
#: pretix/base/models/invoices.py
msgid "currently being transmitted"
msgstr "Siirretään parasta aikaa"
msgstr ""
#: pretix/base/models/invoices.py
#, fuzzy
@@ -5100,7 +5084,7 @@ msgstr "tuntematon"
#: pretix/base/models/invoices.py
msgid "not transmitted due to test mode"
msgstr "ei välitetty testimoodin vuoksi"
msgstr ""
#: pretix/base/models/invoices.py
#, python-format
@@ -8356,8 +8340,6 @@ msgid ""
"Includes the ability to give someone (including oneself) additional "
"permissions."
msgstr ""
"Sisältää mahdollisuuden antaa jollekulle (itsesi mukaanlukien) lisää "
"oikeuksia."
#: pretix/base/permissions.py pretix/control/navigation.py
msgid "Devices"
@@ -8368,8 +8350,6 @@ msgid ""
"Includes the ability to give access to events and data oneself does not have "
"access to."
msgstr ""
"Sisältää mahdollisuuden antaa oikeuksia tapahtumiin ja dataan henkilöllä ei "
"ole vielä oikeuksia."
#: pretix/base/permissions.py
#, fuzzy
@@ -8380,7 +8360,7 @@ msgstr "Istumajärjestys"
#: pretix/base/permissions.py pretix/control/navigation.py
#: pretix/control/templates/pretixcontrol/organizers/outgoing_mails.html
msgid "Outgoing emails"
msgstr "Lähtevät viestit"
msgstr ""
#: pretix/base/plugins.py
#: pretix/control/templates/pretixcontrol/event/quick_setup.html
@@ -8389,19 +8369,19 @@ msgstr "Ominaisuudet"
#: pretix/base/plugins.py
msgid "Integrations"
msgstr "Integraatiot"
msgstr ""
#: pretix/base/plugins.py
msgid "Customizations"
msgstr "Kustomoinnit"
msgstr ""
#: pretix/base/plugins.py
msgid "Output and export formats"
msgstr "Ulostulon ja vientien formaatit"
msgstr ""
#: pretix/base/plugins.py
msgid "API features"
msgstr "API ominaisuudet"
msgstr ""
#: pretix/base/reldate.py
msgid "Event start"
@@ -8463,7 +8443,6 @@ msgstr "Ei asetettu"
#, python-brace-format
msgid "A relative date cannot be expressed as \"before\" for \"{}\""
msgstr ""
"Suhteellista päivämäärää ei voida ilmaista muodossa \"Ennen\" \"{}\" varten"
#: pretix/base/reldate.py
#, python-brace-format
@@ -8499,7 +8478,7 @@ msgstr "Tapahtuma peruttu"
#: pretix/base/services/cancelevent.py
msgid "Confirm event cancellation and bulk refund"
msgstr "Vahvista tapahtuman peruminen ja rahojen palauttaminen massana"
msgstr ""
#: pretix/base/services/cart.py pretix/base/services/modelimport.py
#: pretix/base/services/orders.py
@@ -8533,8 +8512,6 @@ msgid ""
"Some products can no longer be purchased and have been removed from your "
"cart for the following reason: %s"
msgstr ""
"Joitain tuotteista ei voida enää ostaa ja ne on poistettu ostoskoristasi "
"seuraavasta syystä: %s"
#: pretix/base/services/cart.py
msgid ""
@@ -9415,7 +9392,7 @@ msgstr "Kuponkia ei voi luoda ilman koodia."
#, python-brace-format
msgid ""
"Voucher codes must be unique. Code \"{code}\" already exists in this import."
msgstr "Kuponkikoodien täytyy olla uniikkeja. Koodi \"{code}\" on jo olemassa."
msgstr ""
#: pretix/base/services/modelimport.py
#, python-brace-format
@@ -9424,19 +9401,13 @@ msgid ""
msgid_plural ""
"Voucher codes must be unique. Import contains existing voucher codes {code}."
msgstr[0] ""
"Kuponkikoodien tulee olla uniikkeja. Tuoduissa tiedoissa on mukana olemassa "
"oleva kuponkikoodi {code}."
msgstr[1] ""
"Kuponkikoodien tulee olla uniikkeja. Tuoduissa tiedoissa on mukana olemassa "
"olevia kuponkikoodeja {code}."
#: pretix/base/services/modelimport.py
msgid ""
"Vouchers could not be imported, probably due to a voucher code already being "
"in use."
msgstr ""
"Kuponkeja ei voitu tuoda, todennäköisesti koska kupongin koodi on jo "
"käytössä."
#: pretix/base/services/orders.py
msgid ""
@@ -9915,19 +9886,17 @@ msgstr "Kuponki on lähetetty {recipient}."
#: pretix/base/settings.py
msgid "Compute taxes for every line individually"
msgstr "Laske verot jokaiselle riville yksittäin"
msgstr ""
#: pretix/base/settings.py
msgid "Compute taxes based on net total"
msgstr "Laske verot kokonaissumman perusteella"
msgstr ""
#: pretix/base/settings.py
msgid ""
"For business customers, compute taxes based on net total. For individuals, "
"use line-based rounding"
msgstr ""
"Lasket verot nettosumman pohjalta yritysasiakkaille. Käytä rivipohjaista "
"pyöristystä yksityishenkilöille"
#: pretix/base/settings.py
msgid "Compute taxes based on net total with stable gross prices"
@@ -9963,7 +9932,7 @@ msgstr ""
#: pretix/base/settings.py
msgid "Require login to access order confirmation pages"
msgstr "Vaadi kirjautumista tilausvahvistus sivuille pääsyyn"
msgstr ""
#: pretix/base/settings.py
msgid ""
@@ -9972,10 +9941,6 @@ msgid ""
"placing an order, the restriction only becomes active after the customer "
"account is activated."
msgstr ""
"Jos tämä on päällä, käyttäjien, jotka olivat kirjautuneena ostoksen aikana, "
"täytyy kirjautua sisään myös päästäkseen käsiksi tilausvahvistukseensa. Jos "
"käyttäjätili on luotu tilauksen yhteydessä, rajoite astuu voimaan vasta kun "
"käyttäjätili on aktivoitu."
#: pretix/base/settings.py
msgid "Match orders based on email address"
@@ -10177,7 +10142,7 @@ msgstr "Vaaditaan puhelinnumero tilausta kohden"
#: pretix/base/settings.py
msgid "Rounding of taxes"
msgstr "Verojen pyöristys"
msgstr ""
#: pretix/base/settings.py
msgid ""
@@ -10185,10 +10150,6 @@ msgid ""
"for tax reporting, you need to make sure to account for possible rounding "
"differences if your external system rounds differently than pretix."
msgstr ""
"Huomaa, että jos siirrät myyntidataa Pretixistä ulkoiseen järjestelmään "
"verojen ilmoittamista varten, on hyvä varmistaa mahdollisten pyöristys "
"erojen käsittely mikäli ulkoinen järjestelmäsi pyöristää eri tavalla kuin "
"Pretix."
#: pretix/base/settings.py
msgid "Ask for invoice address"
@@ -10332,9 +10293,6 @@ msgid ""
"ID in all countries. VAT ID will be required for all business addresses in "
"the selected countries."
msgstr ""
"Veronumero on vapaaehtoinen oletusarvoisesti, koska kaikkilla yrityksillä ei "
"ole veronumeroa kaikissa maissa. Veronumero vaaditaan kaikilta yritys "
"osoitteilta valituissa maissa."
#: pretix/base/settings.py
msgid "Invoice address explanation"
@@ -10490,12 +10448,12 @@ msgstr ""
#: pretix/base/settings.py
msgid "No dates match your criteria."
msgstr "Yksikään päivämäärä ei vastaa kriteereitäsi."
msgstr ""
#: pretix/base/settings.py
msgctxt "subevents"
msgid "Text for empty date results"
msgstr "Teksti tyhjille päivämäärätuloksille"
msgstr ""
#: pretix/base/settings.py
msgctxt "subevents"
@@ -10506,11 +10464,6 @@ msgid ""
"touch with you to arrange further dates. We do not recommend more than one "
"or two sentences."
msgstr ""
"Tämä teksti näytetään jos kalenteri tai päivämäärälista on tyhjä. "
"Esimerkiksi jos kuukausi ei vastaa päivämäärää tai käyttäjän valitsema "
"filtteriin vastaamia tuloksia ei löydy. Voit käyttää tätä mainostamaan "
"tapoja ottaa yhteyttä teihin tulevien päivämäärien sopimiseksi. Emme "
"suosittele enempää kuin yhtä tai kahta lausetta."
#: pretix/base/settings.py
msgid "Guidance text"
@@ -10695,9 +10648,6 @@ msgid ""
"their order without selecting a payment method. This is useful whenever "
"orders are not created by the same person who is making the payment."
msgstr ""
"Jos maksun viivästäminen on sallittu myyntikanavassa, asiakkaat voivat "
"asettaa tilauksen valitsematta maksutapaa. Tämä on kätevää kun tilaukset "
"eivät ole saman henkilön tekemiä, joka maksaa tilauksen."
#: pretix/base/settings.py
msgid "Show start date"
@@ -10781,13 +10731,10 @@ msgid ""
"Automatic based on ticket-specific validity, membership validity, event "
"series date, or event date"
msgstr ""
"Automaattinen perustuen lippukohtaiseen voimassaoloon, jäsenyyden voimassa "
"oloon, tapahtumasarjan päivämäärään tai tapahtuman päivämäärään"
#: pretix/base/settings.py
msgid "Automatic, but prefer invoice date over event date"
msgstr ""
"Automaattinen, mutta suosi laskun päivämäärää tapahtuman päivämäärän sijaan"
#: pretix/base/settings.py
#, fuzzy
@@ -10808,8 +10755,6 @@ msgid ""
"This controls what dates are shown on the invoice, but is especially "
"important for electronic invoicing."
msgstr ""
"Tämä kontrolloi mitkä päivämäärät näytetään laskulla ja on erityisen tärkeä "
"sähköisessä laskutuksessa."
#: pretix/base/settings.py
msgid "Automatically cancel and reissue invoice on address changes"
@@ -10988,12 +10933,6 @@ msgid ""
"page. Note that pretix still is a system built around events and the date "
"may still show up in other places."
msgstr ""
"Jätä tämä laatikko valitsematta vain jos myyt jotain millä ei ole erillistä "
"päivää, kuten lahjakortti tai lippu, jonka voi käyttää koska tahansa. "
"Järjestelmä lakkaa näyttämästä tapahtuma päivää joissain paikoissa kuten "
"tapahtuman aloitussivulla. Huomaathan että Pretix on silti järjestelmä, joka "
"on rakennettu tapahtumien ympärille ja päivämäärä saatetaan silti näyttää "
"muissa paikoissa."
#: pretix/base/settings.py
msgid "Show event end date"
@@ -13289,7 +13228,7 @@ msgstr "Sinun on vaadittava laskuosoitteet yritysten nimille."
#: pretix/base/settings.py
#, python-brace-format
msgid "VAT-ID is not supported for \"{}\"."
msgstr "Veronumeroa ei tueta \"{}\" varten."
msgstr ""
#: pretix/base/settings.py
msgid "The last payment date cannot be before the end of presale."
@@ -13548,7 +13487,7 @@ msgstr ""
#: pretix/base/templates/pretixbase/email/cancel_confirm.txt
msgid "You requested to cancel an event that involves a large bulk refund:"
msgstr "Pyyntösi perua tapahtuma, joka sisältää suuren massapalautuksen:"
msgstr ""
#: pretix/base/templates/pretixbase/email/cancel_confirm.txt
#, fuzzy
@@ -13558,7 +13497,7 @@ msgstr "Hyvitettävä summa"
#: pretix/base/templates/pretixbase/email/cancel_confirm.txt
msgid "To confirm, paste the following code into the cancellation form:"
msgstr "Vahvistaaksesi kopioi seuraava koodi peruutus lomakkeelle:"
msgstr ""
#: pretix/base/templates/pretixbase/email/cancel_confirm.txt
#, python-format
@@ -13566,7 +13505,6 @@ msgid ""
"Don't share this code with anyone. The %(instance)s team will never ask you "
"for it."
msgstr ""
"Älä jaa tätä koodia kenellekää. %(instance)s tiimi ei koskaan kysy sitä."
#: pretix/base/templates/pretixbase/email/cancel_confirm.txt
#: pretix/base/templates/pretixbase/email/export_failed.txt
@@ -13575,8 +13513,6 @@ msgid ""
"Thanks, \n"
"The %(instance)s Team"
msgstr ""
"Kiitos, \n"
"%(instance)s tiimi"
#: pretix/base/templates/pretixbase/email/email_footer.html
#, python-format
@@ -13622,8 +13558,10 @@ msgstr "Vaihda asetuksia"
#: pretix/base/templates/pretixbase/email/notification.html
#: pretix/base/templates/pretixbase/email/notification.txt
#, fuzzy
#| msgid "Click here disable all notifications immediately."
msgid "Disable all notifications"
msgstr "Poista kaikki ilmoitukset käytöstä"
msgstr "Klikkaa tästä poista kaikki ilmoitukset käytöstä välittömästi."
#: pretix/base/templates/pretixbase/email/order_details.html
msgid ""
@@ -13673,7 +13611,7 @@ msgstr "Saat tämän sähköpostiviestin, koska olet tehnyt {event}tilauksen."
#: pretix/presale/templates/pretixpresale/organizers/customer_memberships.html
#: pretix/presale/templates/pretixpresale/organizers/customer_orders.html
msgid "Details"
msgstr "Yksityiskohdat"
msgstr ""
#: pretix/base/templates/pretixbase/email/order_details.html
#: pretix/presale/templates/pretixpresale/event/base.html
+1 -2
View File
@@ -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))
+3 -2
View File
@@ -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'),
+21
View File
@@ -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/>.
#
+207 -57
View File
@@ -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):
+2 -2
View File
@@ -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,271 +1,298 @@
import type { I18nString, SubEvent } from './i18n'
import type { I18nString, SubEvent } from "./i18n";
const settingsEl = document.getElementById('api-settings')
const { urls } = JSON.parse(settingsEl.textContent || '{}') as { urls: {
lists: string
questions: string
} }
const settingsEl = document.getElementById("api-settings");
const { urls } = JSON.parse(settingsEl.textContent || "{}") as {
urls: {
lists: string;
questions: string;
};
};
// interfaces generated from api docs
export interface PaginatedResponse<T> {
count: number
next: string | null
previous: string | null
results: T[]
count: number;
next: string | null;
previous: string | null;
results: T[];
}
export interface CheckinList {
id: number
name: string
all_products: boolean
limit_products: number[]
subevent: SubEvent | null
position_count?: number
checkin_count?: number
include_pending: boolean
allow_multiple_entries: boolean
allow_entry_after_exit: boolean
rules: Record<string, unknown>
exit_all_at: string | null
addon_match: boolean
ignore_in_statistics?: boolean
consider_tickets_used?: boolean
id: number;
name: string;
all_products: boolean;
limit_products: number[];
subevent: SubEvent | null;
position_count?: number;
checkin_count?: number;
include_pending: boolean;
allow_multiple_entries: boolean;
allow_entry_after_exit: boolean;
rules: Record<string, unknown>;
exit_all_at: string | null;
addon_match: boolean;
ignore_in_statistics?: boolean;
consider_tickets_used?: boolean;
}
export interface Checkin {
id: number
list: number
datetime: string
type: 'entry' | 'exit'
gate: number | null
device: number | null
device_id: number | null
auto_checked_in: boolean
id: number;
list: number;
datetime: string;
type: "entry" | "exit";
gate: number | null;
device: number | null;
device_id: number | null;
auto_checked_in: boolean;
}
export interface Seat {
id: number
name: string
zone_name: string
row_name: string
row_label: string | null
seat_number: string
seat_label: string | null
seat_guid: string
id: number;
name: string;
zone_name: string;
row_name: string;
row_label: string | null;
seat_number: string;
seat_label: string | null;
seat_guid: string;
}
export interface Position {
id: number
order: string
positionid: number
canceled?: boolean
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>
attendee_email: string | null
company?: string | null
street?: string | null
zipcode?: string | null
city?: string | null
country?: string | null
state?: string | null
voucher?: number | null
voucher_budget_use?: string | null
tax_rate: string
tax_value: string
tax_code?: string | null
tax_rule: number | null
secret: string
addon_to: number | null
subevent: SubEvent | null
discount?: number | null
blocked: string[] | null
valid_from: string | null
valid_until: string | null
pseudonymization_id: string
seat: Seat | null
checkins: Checkin[]
downloads?: { output: string; url: string }[]
answers: Answer[]
pdf_data?: Record<string, unknown>
plugin_data?: Record<string, unknown>
id: number;
order: string;
positionid: number;
canceled?: boolean;
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>;
attendee_email: string | null;
company?: string | null;
street?: string | null;
zipcode?: string | null;
city?: string | null;
country?: string | null;
state?: string | null;
voucher?: number | null;
voucher_budget_use?: string | null;
tax_rate: string;
tax_value: string;
tax_code?: string | null;
tax_rule: number | null;
secret: string;
addon_to: number | null;
subevent: SubEvent | null;
discount?: number | null;
blocked: string[] | null;
valid_from: string | null;
valid_until: string | null;
pseudonymization_id: string;
seat: Seat | null;
checkins: Checkin[];
downloads?: { output: string; url: string }[];
answers: Answer[];
pdf_data?: Record<string, unknown>;
plugin_data?: Record<string, unknown>;
// Additional fields from checkin list positions endpoint
order__status?: string
order__valid_if_pending?: boolean
order__require_approval?: boolean
order__locale?: string
require_attention?: boolean
addons?: Addon[]
order__status?: string;
order__valid_if_pending?: boolean;
order__require_approval?: boolean;
order__locale?: string;
require_attention?: boolean;
addons?: Addon[];
}
export interface Answer {
question: number | AnswerQuestion
answer: string
question_identifier: string
options: number[]
option_identifiers: string[]
question: number | AnswerQuestion;
answer: string;
question_identifier: string;
options: number[];
option_identifiers: string[];
}
export interface AnswerQuestion {
id: number
question: I18nString
help_text?: I18nString
type: string
required: boolean
position: number
items: number[]
identifier: string
ask_during_checkin: boolean
show_during_checkin: boolean
hidden?: boolean
print_on_invoice?: boolean
options: QuestionOption[]
valid_number_min?: string | null
valid_number_max?: string | null
valid_date_min?: string | null
valid_date_max?: string | null
valid_datetime_min?: string | null
valid_datetime_max?: string | null
valid_file_portrait?: boolean
valid_string_length_max?: number | null
dependency_question?: number | null
dependency_values?: string[]
id: number;
question: I18nString;
help_text?: I18nString;
type: string;
required: boolean;
position: number;
items: number[];
identifier: string;
ask_during_checkin: boolean;
show_during_checkin: boolean;
hidden?: boolean;
print_on_invoice?: boolean;
options: QuestionOption[];
valid_number_min?: string | null;
valid_number_max?: string | null;
valid_date_min?: string | null;
valid_date_max?: string | null;
valid_datetime_min?: string | null;
valid_datetime_max?: string | null;
valid_file_portrait?: boolean;
valid_string_length_max?: number | null;
dependency_question?: number | null;
dependency_values?: string[];
}
export interface QuestionOption {
id: number
identifier: string
position: number
answer: I18nString
id: number;
identifier: string;
position: number;
answer: I18nString;
}
export interface Addon {
item: { name: I18nString; internal_name?: string }
variation: { value: I18nString } | null
item: { name: I18nString; internal_name?: string };
variation: { value: I18nString } | null;
}
export interface CheckinStatusVariation {
id: number
value: string
checkin_count: number
position_count: number
id: number;
value: string;
checkin_count: number;
position_count: number;
}
export interface CheckinStatusItem {
id: number
name: string
checkin_count: number
admission: boolean
position_count: number
variations: CheckinStatusVariation[]
id: number;
name: string;
checkin_count: number;
admission: boolean;
position_count: number;
variations: CheckinStatusVariation[];
}
export interface CheckinStatus {
checkin_count: number
position_count: number
inside_count: number
event?: { name: string }
items?: CheckinStatusItem[]
checkin_count: number;
position_count: number;
inside_count: number;
event?: { name: string };
items?: CheckinStatusItem[];
}
export interface RedeemRequest {
questions_supported: boolean
canceled_supported: boolean
ignore_unpaid: boolean
type: 'entry' | 'exit'
answers: Record<string, string>
datetime?: string | null
force?: boolean
nonce?: string
questions_supported: boolean;
canceled_supported: boolean;
ignore_unpaid: boolean;
type: "entry" | "exit";
answers: Record<string, string>;
datetime?: string | null;
force?: boolean;
nonce?: string;
}
export interface RedeemResponseList {
id: number
name: string
event: string
subevent: number | null
include_pending: boolean
id: number;
name: string;
event: string;
subevent: number | null;
include_pending: boolean;
}
export interface RedeemResponse {
status: 'ok' | 'error' | 'incomplete'
reason?: 'invalid' | 'unpaid' | 'blocked' | 'invalid_time' | 'canceled' | 'already_redeemed' | 'product' | 'rules' | 'ambiguous' | 'revoked' | 'unapproved' | 'error'
reason_explanation?: string | null
position?: Position
questions?: AnswerQuestion[]
checkin_texts?: string[]
require_attention?: boolean
list?: RedeemResponseList
status: "ok" | "error" | "incomplete";
reason?:
| "invalid"
| "unpaid"
| "blocked"
| "invalid_time"
| "canceled"
| "already_redeemed"
| "product"
| "rules"
| "ambiguous"
| "revoked"
| "unapproved"
| "error";
reason_explanation?: string | null;
position?: Position;
questions?: AnswerQuestion[];
checkin_texts?: string[];
require_attention?: boolean;
list?: RedeemResponseList;
}
const CSRF_TOKEN = document.querySelector<HTMLInputElement>('input[name=csrfmiddlewaretoken]')?.value ?? ''
const CSRF_TOKEN =
document.querySelector<HTMLInputElement>("input[name=csrfmiddlewaretoken]")
?.value ?? "";
function handleAuthError (response: Response): void {
function handleAuthError(response: Response): void {
if ([401, 403].includes(response.status)) {
window.location.href = '/control/login?next=' + encodeURIComponent(
window.location.pathname + window.location.search
) + window.location.hash
window.location.href =
"/control/login?next=" +
encodeURIComponent(window.location.pathname + window.location.search) +
window.location.hash;
}
}
export const api = {
// generic fetch wrapper, not sure if this should be exposed
async fetch <T> (url: string, options?: RequestInit): Promise<T> {
const response = await fetch(url, options)
handleAuthError(response)
async fetch<T>(url: string, options?: RequestInit): Promise<T> {
const response = await fetch(url, options);
handleAuthError(response);
if (!response.ok && response.status !== 400 && response.status !== 404) {
throw new Error('HTTP status ' + response.status)
throw new Error("HTTP status " + response.status);
}
return response.json()
return response.json();
},
async fetchCheckinLists (endsAfter?: string): Promise<PaginatedResponse<CheckinList>> {
const cutoff = endsAfter ?? moment().subtract(8, 'hours').toISOString()
const url = `${urls.lists}?exclude=checkin_count&exclude=position_count&expand=subevent&ends_after=${cutoff}`
return api.fetch(url)
async fetchCheckinLists(
endsAfter?: string,
): Promise<PaginatedResponse<CheckinList>> {
const cutoff = endsAfter ?? moment().subtract(8, "hours").toISOString();
const url = `${urls.lists}?exclude=checkin_count&exclude=position_count&expand=subevent&ends_after=${cutoff}`;
return api.fetch(url);
},
async fetchCheckinList (listId: string): Promise<CheckinList> {
return api.fetch(`${urls.lists}${listId}/?expand=subevent`)
async fetchCheckinList(listId: string): Promise<CheckinList> {
return api.fetch(`${urls.lists}${listId}/?expand=subevent`);
},
async fetchNextPage<T> (nextUrl: string): Promise<PaginatedResponse<T>> {
return api.fetch(nextUrl)
async fetchNextPage<T>(nextUrl: string): Promise<PaginatedResponse<T>> {
return api.fetch(nextUrl);
},
async fetchStatus (listId: number): Promise<CheckinStatus> {
return api.fetch(`${urls.lists}${listId}/status/`)
async fetchStatus(listId: number): Promise<CheckinStatus> {
return api.fetch(`${urls.lists}${listId}/status/`);
},
async searchPositions (listId: number, query: string): Promise<PaginatedResponse<Position>> {
const url = `${urls.lists}${listId}/positions/?ignore_status=true&expand=subevent&expand=item&expand=variation&check_rules=true&search=${encodeURIComponent(query)}`
return api.fetch(url)
async searchPositions(
listId: number,
query: string,
): Promise<PaginatedResponse<Position>> {
const url = `${urls.lists}${listId}/positions/?ignore_status=true&expand=subevent&expand=item&expand=variation&check_rules=true&search=${encodeURIComponent(query)}`;
return api.fetch(url);
},
async redeemPosition (
async redeemPosition(
listId: number,
positionId: string,
data: RedeemRequest,
untrusted: boolean = false
untrusted: boolean = false,
): Promise<RedeemResponse> {
let url = `${urls.lists}${listId}/positions/${encodeURIComponent(positionId)}/redeem/?expand=item&expand=subevent&expand=variation&expand=answers.question&expand=addons`
if (untrusted) url += '&untrusted_input=true'
let url = `${urls.lists}${listId}/positions/${encodeURIComponent(positionId)}/redeem/?expand=item&expand=subevent&expand=variation&expand=answers.question&expand=addons`;
if (untrusted) url += "&untrusted_input=true";
const response = await fetch(url, {
method: 'POST',
method: "POST",
headers: {
'X-CSRFToken': CSRF_TOKEN,
'Content-Type': 'application/json',
"X-CSRFToken": CSRF_TOKEN,
"Content-Type": "application/json",
},
body: JSON.stringify(data),
})
});
handleAuthError(response)
handleAuthError(response);
if (response.status === 404) {
return { status: 'error', reason: 'invalid' }
return { status: "error", reason: "invalid" };
}
if (!response.ok && response.status !== 400) {
throw new Error('HTTP status ' + response.status)
throw new Error("HTTP status " + response.status);
}
return response.json()
}
}
return response.json();
},
};
@@ -1,292 +1,316 @@
<script setup lang="ts">
import { ref, computed, nextTick, onMounted, onUnmounted } from 'vue'
import { api } from '../api'
import type { CheckinList, Position, RedeemResponse, CheckinStatus, AnswerQuestion } from '../api'
import { STRINGS, i18nstringLocalize, formatSubevent, formatAnswer } from '../i18n'
import { ref, computed, nextTick, onMounted, onUnmounted } from "vue";
import { api } from "../api";
import type {
CheckinList,
Position,
RedeemResponse,
CheckinStatus,
AnswerQuestion,
} from "../api";
import {
STRINGS,
i18nstringLocalize,
formatSubevent,
formatAnswer,
} from "../i18n";
import CheckinlistSelect from './checkinlist-select.vue'
import SearchresultItem from './searchresult-item.vue'
import Datefield from './datefield.vue'
import Timefield from './timefield.vue'
import Datetimefield from './datetimefield.vue'
import CheckinlistSelect from "./checkinlist-select.vue";
import SearchresultItem from "./searchresult-item.vue";
import Datefield from "./datefield.vue";
import Timefield from "./timefield.vue";
import Datetimefield from "./datetimefield.vue";
const props = defineProps<{
eventName?: string
}>()
eventName?: string;
}>();
const COUNTRIES = JSON.parse(document.querySelector('#countries')?.textContent ?? '[]')
const COUNTRIES = JSON.parse(
document.querySelector("#countries")?.textContent ?? "[]",
);
let clearTimeoutId: ReturnType<typeof setTimeout> | null = null
const answers = ref<Record<string, string>>({})
let clearTimeoutId: ReturnType<typeof setTimeout> | null = null;
const answers = ref<Record<string, string>>({});
// Checkin list selection
const checkinlist = ref<CheckinList | null>(null)
const subevent = computed(() => formatSubevent(checkinlist.value?.subevent))
const checkinlist = ref<CheckinList | null>(null);
const subevent = computed(() => formatSubevent(checkinlist.value?.subevent));
function selectList (list: CheckinList) {
checkinlist.value = list
location.hash = '#' + list.id
refocus()
fetchStatus()
function selectList(list: CheckinList) {
checkinlist.value = list;
location.hash = "#" + list.id;
refocus();
fetchStatus();
}
function switchList () {
location.hash = ''
checkinlist.value = null
function switchList() {
location.hash = "";
checkinlist.value = null;
}
// Entry/Exit type
const type = ref<'entry' | 'exit'>('entry')
const type = ref<"entry" | "exit">("entry");
function switchType () {
type.value = type.value === 'exit' ? 'entry' : 'exit'
refocus()
function switchType() {
type.value = type.value === "exit" ? "entry" : "exit";
refocus();
}
// Input/query
const inputEl = ref<HTMLInputElement>()
const query = ref('')
const inputEl = ref<HTMLInputElement>();
const query = ref("");
function refocus () {
function refocus() {
nextTick(() => {
inputEl.value?.focus()
})
inputEl.value?.focus();
});
}
function inputKeyup (e: KeyboardEvent) {
if (e.key === 'Enter') {
startSearch(true)
} else if (query.value === '') {
clear()
function inputKeyup(e: KeyboardEvent) {
if (e.key === "Enter") {
startSearch(true);
} else if (query.value === "") {
clear();
}
}
function globalKeydown (e: KeyboardEvent | Event) {
function globalKeydown(e: KeyboardEvent | Event) {
if (!(e instanceof KeyboardEvent)) {
refocus()
return
refocus();
return;
}
if (document.activeElement?.classList.contains('searchresult')) {
if (e.key === 'ArrowDown') {
(document.activeElement.nextElementSibling as HTMLElement)?.focus()
e.preventDefault()
return
if (document.activeElement?.classList.contains("searchresult")) {
if (e.key === "ArrowDown") {
(document.activeElement.nextElementSibling as HTMLElement)?.focus();
e.preventDefault();
return;
}
if (e.key === 'ArrowUp') {
(document.activeElement.previousElementSibling as HTMLElement)?.focus()
e.preventDefault()
return
if (e.key === "ArrowUp") {
(document.activeElement.previousElementSibling as HTMLElement)?.focus();
e.preventDefault();
return;
}
}
const nodeName = document.activeElement?.nodeName?.toLowerCase()
if (nodeName !== 'input' && nodeName !== 'textarea') {
const nodeName = document.activeElement?.nodeName?.toLowerCase();
if (nodeName !== "input" && nodeName !== "textarea") {
if (e.key?.match(/^[a-z0-9A-Z+/=<>#]$/)) {
query.value = ''
refocus()
query.value = "";
refocus();
}
}
}
// Status
const status = ref<CheckinStatus | null>(null)
const statusLoading = ref(0)
let statusInterval: ReturnType<typeof setInterval> | null = null
const status = ref<CheckinStatus | null>(null);
const statusLoading = ref(0);
let statusInterval: ReturnType<typeof setInterval> | null = null;
async function fetchStatus () {
if (!checkinlist.value) return
async function fetchStatus() {
if (!checkinlist.value) return;
statusLoading.value++
statusLoading.value++;
try {
status.value = await api.fetchStatus(checkinlist.value.id)
status.value = await api.fetchStatus(checkinlist.value.id);
} finally {
statusLoading.value--
statusLoading.value--;
}
}
// Check/redeem
const checkLoading = ref(false)
const checkError = ref<string | null>(null)
const checkResult = ref<RedeemResponse | null>(null)
const checkLoading = ref(false);
const checkError = ref<string | null>(null);
const checkResult = ref<RedeemResponse | null>(null);
const checkResultAddons = computed(() => {
if (!checkResult.value?.position?.addons) return ''
return checkResult.value.position.addons.map((addon) => {
if (addon.variation) {
return `+ ${addon.item.internal_name || i18nstringLocalize(addon.item.name)} – ${i18nstringLocalize(addon.variation.value)}`
}
return '+ ' + (addon.item.internal_name || i18nstringLocalize(addon.item.name))
}).join('\n')
})
if (!checkResult.value?.position?.addons) return "";
return checkResult.value.position.addons
.map((addon) => {
if (addon.variation) {
return `+ ${addon.item.internal_name || i18nstringLocalize(addon.item.name)} – ${i18nstringLocalize(addon.variation.value)}`;
}
return (
"+ " + (addon.item.internal_name || i18nstringLocalize(addon.item.name))
);
})
.join("\n");
});
const checkResultSubevent = computed(() => formatSubevent(checkResult.value?.position?.subevent))
const checkResultSubevent = computed(() =>
formatSubevent(checkResult.value?.position?.subevent),
);
const checkResultItemvar = computed(() => {
if (!checkResult.value?.position) return ''
if (!checkResult.value?.position) return "";
if (checkResult.value.position.variation) {
return `${i18nstringLocalize(checkResult.value.position.item.name)} – ${i18nstringLocalize(checkResult.value.position.variation.value)}`
return `${i18nstringLocalize(checkResult.value.position.item.name)} – ${i18nstringLocalize(checkResult.value.position.variation.value)}`;
}
return i18nstringLocalize(checkResult.value.position.item.name)
})
return i18nstringLocalize(checkResult.value.position.item.name);
});
const checkResultText = computed(() => {
if (!checkResult.value) return ''
if (checkResult.value.status === 'ok') {
return type.value === 'exit' ? STRINGS['result.exit'] : STRINGS['result.ok']
} else if (checkResult.value.status === 'incomplete') {
return STRINGS['result.questions']
} else if (checkResult.value.reason && STRINGS['result.' + checkResult.value.reason]) {
return STRINGS['result.' + checkResult.value.reason]
if (!checkResult.value) return "";
if (checkResult.value.status === "ok") {
return type.value === "exit"
? STRINGS["result.exit"]
: STRINGS["result.ok"];
} else if (checkResult.value.status === "incomplete") {
return STRINGS["result.questions"];
} else if (
checkResult.value.reason &&
STRINGS["result." + checkResult.value.reason]
) {
return STRINGS["result." + checkResult.value.reason];
}
return checkResult.value.reason ?? ''
})
return checkResult.value.reason ?? "";
});
const checkResultColor = computed(() => {
if (!checkResult.value) return ''
if (checkResult.value.status === 'ok') return 'green'
if (checkResult.value.status === 'incomplete') return 'purple'
if (checkResult.value.reason === 'already_redeemed') return 'orange'
return 'red'
})
if (!checkResult.value) return "";
if (checkResult.value.status === "ok") return "green";
if (checkResult.value.status === "incomplete") return "purple";
if (checkResult.value.reason === "already_redeemed") return "orange";
return "red";
});
// Modals
const showUnpaidModal = ref(false)
const showQuestionsModal = ref(false)
const questionsModalEl = ref<HTMLFormElement>()
const showUnpaidModal = ref(false);
const showQuestionsModal = ref(false);
const questionsModalEl = ref<HTMLFormElement>();
function answerSetM (qid: string, opid: string, checked: boolean) {
let arr = answers.value[qid] ? answers.value[qid].split(',') : []
function answerSetM(qid: string, opid: string, checked: boolean) {
let arr = answers.value[qid] ? answers.value[qid].split(",") : [];
if (checked && !arr.includes(opid)) {
arr.push(opid)
arr.push(opid);
} else if (!checked) {
arr = arr.filter(o => opid !== o)
arr = arr.filter((o) => opid !== o);
}
answers.value[qid] = arr.join(',')
answers.value[qid] = arr.join(",");
}
// Search
const searchLoading = ref(false)
const searchResults = ref<Position[] | null>(null)
const searchNextUrl = ref<string | null>(null)
const searchError = ref<unknown>(null)
const resultEls = ref<InstanceType<typeof SearchresultItem>[]>([])
const searchLoading = ref(false);
const searchResults = ref<Position[] | null>(null);
const searchNextUrl = ref<string | null>(null);
const searchError = ref<unknown>(null);
const resultEls = ref<InstanceType<typeof SearchresultItem>[]>([]);
function selectResult (position: Position) {
check(position.secret, false, false, false, false)
function selectResult(position: Position) {
check(position.secret, false, false, false, false);
}
async function startSearch (fallbackToScan: boolean) {
async function startSearch(fallbackToScan: boolean) {
if (query.value.length >= 32 && fallbackToScan) {
check(query.value, false, false, true, true)
return
check(query.value, false, false, true, true);
return;
}
checkResult.value = null
searchLoading.value = true
searchError.value = null
searchResults.value = []
answers.value = {}
checkResult.value = null;
searchLoading.value = true;
searchError.value = null;
searchResults.value = [];
answers.value = {};
if (clearTimeoutId) {
clearTimeout(clearTimeoutId)
clearTimeoutId = null
clearTimeout(clearTimeoutId);
clearTimeoutId = null;
}
try {
const data = await api.searchPositions(checkinlist.value!.id, query.value)
searchLoading.value = false
const data = await api.searchPositions(checkinlist.value!.id, query.value);
searchLoading.value = false;
if (data.results) {
searchResults.value = data.results
searchNextUrl.value = data.next
searchResults.value = data.results;
searchNextUrl.value = data.next;
if (data.results.length) {
if (data.results[0].secret === query.value) {
nextTick(() => {
inputEl.value?.blur()
resultEls.value[0]?.el?.click()
})
inputEl.value?.blur();
resultEls.value[0]?.el?.click();
});
} else {
nextTick(() => {
resultEls.value[0]?.el?.focus()
})
resultEls.value[0]?.el?.focus();
});
}
} else {
nextTick(() => {
inputEl.value?.blur()
})
inputEl.value?.blur();
});
}
} else {
searchError.value = data
searchError.value = data;
}
clearTimeoutId = setTimeout(clear, 30 * 1000)
clearTimeoutId = setTimeout(clear, 30 * 1000);
} catch (e) {
searchLoading.value = false
searchResults.value = []
searchError.value = e
clearTimeoutId = setTimeout(clear, 30 * 1000)
searchLoading.value = false;
searchResults.value = [];
searchError.value = e;
clearTimeoutId = setTimeout(clear, 30 * 1000);
}
}
async function searchNext () {
if (!searchNextUrl.value) return
async function searchNext() {
if (!searchNextUrl.value) return;
searchLoading.value = true
searchError.value = null
searchLoading.value = true;
searchError.value = null;
if (clearTimeoutId) {
clearTimeout(clearTimeoutId)
clearTimeoutId = null
clearTimeout(clearTimeoutId);
clearTimeoutId = null;
}
try {
const data = await api.fetchNextPage<Position>(searchNextUrl.value)
searchLoading.value = false
const data = await api.fetchNextPage<Position>(searchNextUrl.value);
searchLoading.value = false;
if (data.results) {
searchResults.value = [...(searchResults.value ?? []), ...data.results]
searchNextUrl.value = data.next
searchResults.value = [...(searchResults.value ?? []), ...data.results];
searchNextUrl.value = data.next;
} else {
searchError.value = data
searchError.value = data;
}
clearTimeoutId = setTimeout(clear, 30 * 1000)
clearTimeoutId = setTimeout(clear, 30 * 1000);
} catch (e) {
searchLoading.value = false
searchError.value = e
clearTimeoutId = setTimeout(clear, 30 * 1000)
searchLoading.value = false;
searchError.value = e;
clearTimeoutId = setTimeout(clear, 30 * 1000);
}
}
async function check (
async function check(
id: string,
ignoreUnpaid: boolean,
keepAnswers: boolean,
fallbackToSearch: boolean,
untrusted: boolean
untrusted: boolean,
) {
if (!keepAnswers) {
answers.value = {}
answers.value = {};
} else if (showQuestionsModal.value) {
if (!questionsModalEl.value?.reportValidity()) return
if (!questionsModalEl.value?.reportValidity()) return;
}
showUnpaidModal.value = false
showQuestionsModal.value = false
checkLoading.value = true
checkError.value = null
checkResult.value = {} as RedeemResponse
showUnpaidModal.value = false;
showQuestionsModal.value = false;
checkLoading.value = true;
checkError.value = null;
checkResult.value = {} as RedeemResponse;
if (clearTimeoutId) {
clearTimeout(clearTimeoutId)
clearTimeoutId = null
clearTimeout(clearTimeoutId);
clearTimeoutId = null;
}
nextTick(() => {
inputEl.value?.blur()
})
inputEl.value?.blur();
});
try {
const data = await api.redeemPosition(
@@ -299,73 +323,87 @@ async function check (
type: type.value,
answers: answers.value,
},
untrusted
)
untrusted,
);
checkLoading.value = false
checkResult.value = data
checkLoading.value = false;
checkResult.value = data;
if (checkinlist.value?.include_pending && data.status === 'error' && data.reason === 'unpaid') {
showUnpaidModal.value = true
if (
checkinlist.value?.include_pending &&
data.status === "error" &&
data.reason === "unpaid"
) {
showUnpaidModal.value = true;
nextTick(() => {
document.querySelector<HTMLButtonElement>('.modal-unpaid .btn-primary')?.focus()
})
} else if (data.status === 'incomplete' && data.questions) {
showQuestionsModal.value = true
document
.querySelector<HTMLButtonElement>(".modal-unpaid .btn-primary")
?.focus();
});
} else if (data.status === "incomplete" && data.questions) {
showQuestionsModal.value = true;
for (const q of data.questions) {
if (!answers.value[q.id.toString()]) {
answers.value[q.id.toString()] = ''
answers.value[q.id.toString()] = "";
}
;(q as AnswerQuestion).question = i18nstringLocalize(q.question)
(q as AnswerQuestion).question = i18nstringLocalize(q.question);
for (const o of q.options) {
;(o as { answer: string }).answer = i18nstringLocalize(o.answer)
(o as { answer: string }).answer = i18nstringLocalize(o.answer);
}
}
nextTick(() => {
document.querySelector<HTMLElement>('.modal-questions input, .modal-questions select, .modal-questions textarea')?.focus()
})
} else if (data.status === 'error' && data.reason === 'invalid' && fallbackToSearch) {
startSearch(false)
document
.querySelector<HTMLElement>(
".modal-questions input, .modal-questions select, .modal-questions textarea",
)
?.focus();
});
} else if (
data.status === "error" &&
data.reason === "invalid" &&
fallbackToSearch
) {
startSearch(false);
} else {
clearTimeoutId = setTimeout(clear, 30 * 1000)
fetchStatus()
clearTimeoutId = setTimeout(clear, 30 * 1000);
fetchStatus();
}
} catch (e) {
checkLoading.value = false
checkResult.value = {} as RedeemResponse
checkError.value = String(e)
clearTimeoutId = setTimeout(clear, 30 * 1000)
checkLoading.value = false;
checkResult.value = {} as RedeemResponse;
checkError.value = String(e);
clearTimeoutId = setTimeout(clear, 30 * 1000);
}
}
function clear () {
query.value = ''
searchLoading.value = false
searchResults.value = null
searchNextUrl.value = null
searchError.value = null
checkLoading.value = false
checkError.value = null
checkResult.value = null
showUnpaidModal.value = false
showQuestionsModal.value = false
answers.value = {}
function clear() {
query.value = "";
searchLoading.value = false;
searchResults.value = null;
searchNextUrl.value = null;
searchError.value = null;
checkLoading.value = false;
checkError.value = null;
checkResult.value = null;
showUnpaidModal.value = false;
showQuestionsModal.value = false;
answers.value = {};
}
onMounted(() => {
window.addEventListener('focus', globalKeydown)
document.addEventListener('visibilitychange', globalKeydown)
document.addEventListener('keydown', globalKeydown)
statusInterval = setInterval(fetchStatus, 120 * 1000)
})
window.addEventListener("focus", globalKeydown);
document.addEventListener("visibilitychange", globalKeydown);
document.addEventListener("keydown", globalKeydown);
statusInterval = setInterval(fetchStatus, 120 * 1000);
});
onUnmounted(() => {
window.removeEventListener('focus', globalKeydown)
document.removeEventListener('visibilitychange', globalKeydown)
document.removeEventListener('keydown', globalKeydown)
if (statusInterval) clearInterval(statusInterval)
if (clearTimeoutId) clearTimeout(clearTimeoutId)
})
window.removeEventListener("focus", globalKeydown);
document.removeEventListener("visibilitychange", globalKeydown);
document.removeEventListener("keydown", globalKeydown);
if (statusInterval) clearInterval(statusInterval);
if (clearTimeoutId) clearTimeout(clearTimeoutId);
});
</script>
<template lang="pug">
.container
@@ -1,17 +1,17 @@
<script setup lang="ts">
import { computed } from 'vue'
import type { CheckinList } from '../api'
import { formatSubevent } from '../i18n'
import { computed } from "vue";
import type { CheckinList } from "../api";
import { formatSubevent } from "../i18n";
const props = defineProps<{
list: CheckinList
}>()
list: CheckinList;
}>();
defineEmits<{
selected: [list: CheckinList]
}>()
selected: [list: CheckinList];
}>();
const subevent = computed(() => formatSubevent(props.list.subevent))
const subevent = computed(() => formatSubevent(props.list.subevent));
</script>
<template lang="pug">
a.list-group-item(href="#", @click.prevent="$emit('selected', list)")
@@ -1,86 +1,86 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { api } from '../api'
import type { CheckinList } from '../api'
import { STRINGS } from '../i18n'
import CheckinlistItem from './checkinlist-item.vue'
import { ref, onMounted } from "vue";
import { api } from "../api";
import type { CheckinList } from "../api";
import { STRINGS } from "../i18n";
import CheckinlistItem from "./checkinlist-item.vue";
const emit = defineEmits<{
selected: [list: CheckinList]
}>()
selected: [list: CheckinList];
}>();
const loading = ref(false)
const error = ref<unknown>(null)
const lists = ref<CheckinList[] | null>(null)
const nextUrl = ref<string | null>(null)
const loading = ref(false);
const error = ref<unknown>(null);
const lists = ref<CheckinList[] | null>(null);
const nextUrl = ref<string | null>(null);
async function load () {
loading.value = true
error.value = null
async function load() {
loading.value = true;
error.value = null;
try {
if (location.hash) {
const listId = location.hash.substring(1)
const listId = location.hash.substring(1);
try {
const data = await api.fetchCheckinList(listId)
loading.value = false
const data = await api.fetchCheckinList(listId);
loading.value = false;
if (data.id) {
emit('selected', data)
emit("selected", data);
} else {
location.hash = ''
load()
location.hash = "";
load();
}
} catch {
location.hash = ''
load()
location.hash = "";
load();
}
return
return;
}
const data = await api.fetchCheckinLists()
loading.value = false
const data = await api.fetchCheckinLists();
loading.value = false;
if (data.results) {
lists.value = data.results
nextUrl.value = data.next
lists.value = data.results;
nextUrl.value = data.next;
} else if (data.results === 0) {
error.value = STRINGS['checkinlist.none']
error.value = STRINGS["checkinlist.none"];
} else {
error.value = data
error.value = data;
}
} catch (e) {
loading.value = false
error.value = e
loading.value = false;
error.value = e;
}
}
async function loadNext () {
if (!nextUrl.value) return
async function loadNext() {
if (!nextUrl.value) return;
loading.value = true
error.value = null
loading.value = true;
error.value = null;
try {
const data = await api.fetchNextPage<CheckinList>(nextUrl.value)
loading.value = false
const data = await api.fetchNextPage<CheckinList>(nextUrl.value);
loading.value = false;
if (data.results) {
lists.value.push(...data.results)
nextUrl.value = data.next
lists.value.push(...data.results);
nextUrl.value = data.next;
} else if (data.results === 0) {
error.value = STRINGS['checkinlist.none']
error.value = STRINGS["checkinlist.none"];
} else {
error.value = data
error.value = data;
}
} catch (e) {
loading.value = false
error.value = e
loading.value = false;
error.value = e;
}
}
onMounted(() => {
load()
})
load();
});
</script>
<template lang="pug">
.panel.panel-primary.checkinlist-select
@@ -1,18 +1,18 @@
<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted } from 'vue'
import { dateFormat, datetimeLocale } from '../i18n'
import { ref, watch, onMounted, onUnmounted } from "vue";
import { dateFormat, datetimeLocale } from "../i18n";
const props = defineProps<{
required?: boolean
modelValue?: string
id?: string
}>()
required?: boolean;
modelValue?: string;
id?: string;
}>();
const emit = defineEmits<{
'update:modelValue': [value: string]
}>()
"update:modelValue": [value: string];
}>();
const input = ref<HTMLInputElement>()
const input = ref<HTMLInputElement>();
const opts = {
format: dateFormat,
@@ -20,44 +20,50 @@ const opts = {
useCurrent: false,
showClear: props.required,
icons: {
time: 'fa fa-clock-o',
date: 'fa fa-calendar',
up: 'fa fa-chevron-up',
down: 'fa fa-chevron-down',
previous: 'fa fa-chevron-left',
next: 'fa fa-chevron-right',
today: 'fa fa-screenshot',
clear: 'fa fa-trash',
close: 'fa fa-remove',
time: "fa fa-clock-o",
date: "fa fa-calendar",
up: "fa fa-chevron-up",
down: "fa fa-chevron-down",
previous: "fa fa-chevron-left",
next: "fa fa-chevron-right",
today: "fa fa-screenshot",
clear: "fa fa-trash",
close: "fa fa-remove",
},
}
};
watch(() => props.modelValue, (val) => {
if (val) {
$(input.value!).data('DateTimePicker').date(moment(val))
}
})
watch(
() => props.modelValue,
(val) => {
if (val) {
$(input.value!).data("DateTimePicker").date(moment(val));
}
},
);
onMounted(() => {
$(input.value!)
.datetimepicker(opts)
.trigger('change')
.on('dp.change', function (this: HTMLElement) {
emit('update:modelValue', $(this).data('DateTimePicker').date().format('YYYY-MM-DD'))
})
.trigger("change")
.on("dp.change", function (this: HTMLElement) {
emit(
"update:modelValue",
$(this).data("DateTimePicker").date().format("YYYY-MM-DD"),
);
});
if (!props.modelValue) {
$(input.value!).data('DateTimePicker').viewDate(moment().hour(0).minute(0).second(0).millisecond(0))
$(input.value!)
.data("DateTimePicker")
.viewDate(moment().hour(0).minute(0).second(0).millisecond(0));
} else {
$(input.value!).data('DateTimePicker').date(moment(props.modelValue))
$(input.value!).data("DateTimePicker").date(moment(props.modelValue));
}
})
});
onUnmounted(() => {
$(input.value!)
.off()
.datetimepicker('destroy')
})
$(input.value!).off().datetimepicker("destroy");
});
</script>
<template lang="pug">
input.form-control(:id="id", ref="input", :required="required")
@@ -1,18 +1,18 @@
<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted } from 'vue'
import { datetimeFormat, datetimeLocale, timezone } from '../i18n'
import { ref, watch, onMounted, onUnmounted } from "vue";
import { datetimeFormat, datetimeLocale, timezone } from "../i18n";
const props = defineProps<{
required?: boolean
modelValue?: string
id?: string
}>()
required?: boolean;
modelValue?: string;
id?: string;
}>();
const emit = defineEmits<{
'update:modelValue': [value: string]
}>()
"update:modelValue": [value: string];
}>();
const input = ref<HTMLInputElement>()
const input = ref<HTMLInputElement>();
const opts = {
format: datetimeFormat,
@@ -21,44 +21,50 @@ const opts = {
useCurrent: false,
showClear: props.required,
icons: {
time: 'fa fa-clock-o',
date: 'fa fa-calendar',
up: 'fa fa-chevron-up',
down: 'fa fa-chevron-down',
previous: 'fa fa-chevron-left',
next: 'fa fa-chevron-right',
today: 'fa fa-screenshot',
clear: 'fa fa-trash',
close: 'fa fa-remove',
time: "fa fa-clock-o",
date: "fa fa-calendar",
up: "fa fa-chevron-up",
down: "fa fa-chevron-down",
previous: "fa fa-chevron-left",
next: "fa fa-chevron-right",
today: "fa fa-screenshot",
clear: "fa fa-trash",
close: "fa fa-remove",
},
}
};
watch(() => props.modelValue, (val) => {
if (val) {
$(input.value!).data('DateTimePicker').date(moment(val))
}
})
watch(
() => props.modelValue,
(val) => {
if (val) {
$(input.value!).data("DateTimePicker").date(moment(val));
}
},
);
onMounted(() => {
$(input.value!)
.datetimepicker(opts)
.trigger('change')
.on('dp.change', function (this: HTMLElement) {
emit('update:modelValue', $(this).data('DateTimePicker').date().toISOString())
})
.trigger("change")
.on("dp.change", function (this: HTMLElement) {
emit(
"update:modelValue",
$(this).data("DateTimePicker").date().toISOString(),
);
});
if (!props.modelValue) {
$(input.value!).data('DateTimePicker').viewDate(moment().hour(0).minute(0).second(0).millisecond(0))
$(input.value!)
.data("DateTimePicker")
.viewDate(moment().hour(0).minute(0).second(0).millisecond(0));
} else {
$(input.value!).data('DateTimePicker').date(moment(props.modelValue))
$(input.value!).data("DateTimePicker").date(moment(props.modelValue));
}
})
});
onUnmounted(() => {
$(input.value!)
.off()
.datetimepicker('destroy')
})
$(input.value!).off().datetimepicker("destroy");
});
</script>
<template lang="pug">
input.form-control(:id="id", ref="input", :required="required")
@@ -1,35 +1,43 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import type { Position } from '../api'
import { STRINGS, i18nstringLocalize, formatSubevent } from '../i18n'
import { computed, ref } from "vue";
import type { Position } from "../api";
import { STRINGS, i18nstringLocalize, formatSubevent } from "../i18n";
const props = defineProps<{
position: Position
}>()
position: Position;
}>();
defineEmits<{
selected: [position: Position]
}>()
selected: [position: Position];
}>();
const rootEl = ref<HTMLAnchorElement>()
const rootEl = ref<HTMLAnchorElement>();
const status = computed(() => {
if (props.position.checkins.length) return 'redeemed'
if (props.position.order__status === 'n' && props.position.order__valid_if_pending) return 'pending_valid'
if (props.position.order__status === 'n' && props.position.order__require_approval) return 'require_approval'
return props.position.order__status
})
if (props.position.checkins.length) return "redeemed";
if (
props.position.order__status === "n" &&
props.position.order__valid_if_pending
)
return "pending_valid";
if (
props.position.order__status === "n" &&
props.position.order__require_approval
)
return "require_approval";
return props.position.order__status;
});
const itemvar = computed(() => {
if (props.position.variation) {
return `${i18nstringLocalize(props.position.item.name)} – ${i18nstringLocalize(props.position.variation.value)}`
return `${i18nstringLocalize(props.position.item.name)} – ${i18nstringLocalize(props.position.variation.value)}`;
}
return i18nstringLocalize(props.position.item.name)
})
return i18nstringLocalize(props.position.item.name);
});
const subevent = computed(() => formatSubevent(props.position.subevent))
const subevent = computed(() => formatSubevent(props.position.subevent));
defineExpose({ el: rootEl })
defineExpose({ el: rootEl });
</script>
<template lang="pug">
a.list-group-item.searchresult(ref="rootEl", href="#", @click.prevent="$emit('selected', position)")
@@ -1,18 +1,18 @@
<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted } from 'vue'
import { timeFormat, datetimeLocale } from '../i18n'
import { ref, watch, onMounted, onUnmounted } from "vue";
import { timeFormat, datetimeLocale } from "../i18n";
const props = defineProps<{
required?: boolean
modelValue?: string
id?: string
}>()
required?: boolean;
modelValue?: string;
id?: string;
}>();
const emit = defineEmits<{
'update:modelValue': [value: string]
}>()
"update:modelValue": [value: string];
}>();
const input = ref<HTMLInputElement>()
const input = ref<HTMLInputElement>();
const opts = {
format: timeFormat,
@@ -20,44 +20,50 @@ const opts = {
useCurrent: false,
showClear: props.required,
icons: {
time: 'fa fa-clock-o',
date: 'fa fa-calendar',
up: 'fa fa-chevron-up',
down: 'fa fa-chevron-down',
previous: 'fa fa-chevron-left',
next: 'fa fa-chevron-right',
today: 'fa fa-screenshot',
clear: 'fa fa-trash',
close: 'fa fa-remove',
time: "fa fa-clock-o",
date: "fa fa-calendar",
up: "fa fa-chevron-up",
down: "fa fa-chevron-down",
previous: "fa fa-chevron-left",
next: "fa fa-chevron-right",
today: "fa fa-screenshot",
clear: "fa fa-trash",
close: "fa fa-remove",
},
}
};
watch(() => props.modelValue, (val) => {
if (val) {
$(input.value!).data('DateTimePicker').date(moment(val))
}
})
watch(
() => props.modelValue,
(val) => {
if (val) {
$(input.value!).data("DateTimePicker").date(moment(val));
}
},
);
onMounted(() => {
$(input.value!)
.datetimepicker(opts)
.trigger('change')
.on('dp.change', function (this: HTMLElement) {
emit('update:modelValue', $(this).data('DateTimePicker').date().format('HH:mm:ss'))
})
.trigger("change")
.on("dp.change", function (this: HTMLElement) {
emit(
"update:modelValue",
$(this).data("DateTimePicker").date().format("HH:mm:ss"),
);
});
if (!props.modelValue) {
$(input.value!).data('DateTimePicker').viewDate(moment().hour(0).minute(0).second(0).millisecond(0))
$(input.value!)
.data("DateTimePicker")
.viewDate(moment().hour(0).minute(0).second(0).millisecond(0));
} else {
$(input.value!).data('DateTimePicker').date(moment(props.modelValue))
$(input.value!).data("DateTimePicker").date(moment(props.modelValue));
}
})
});
onUnmounted(() => {
$(input.value!)
.off()
.datetimepicker('destroy')
})
$(input.value!).off().datetimepicker("destroy");
});
</script>
<template lang="pug">
input.form-control(:id="id", ref="input", :required="required")
@@ -1,106 +1,115 @@
const body = document.body
const body = document.body;
export const timezone = body.dataset.timezone ?? 'UTC'
export const datetimeFormat = body.dataset.datetimeformat ?? 'L LT'
export const dateFormat = body.dataset.dateformat ?? 'L'
export const timeFormat = body.dataset.timeformat ?? 'LT'
export const datetimeLocale = body.dataset.datetimelocale ?? 'en'
export const pretixLocale = body.dataset.pretixlocale ?? 'en'
export const timezone = body.dataset.timezone ?? "UTC";
export const datetimeFormat = body.dataset.datetimeformat ?? "L LT";
export const dateFormat = body.dataset.dateformat ?? "L";
export const timeFormat = body.dataset.timeformat ?? "LT";
export const datetimeLocale = body.dataset.datetimelocale ?? "en";
export const pretixLocale = body.dataset.pretixlocale ?? "en";
moment.locale(datetimeLocale)
moment.locale(datetimeLocale);
export function gettext (msgid: string): string {
if (typeof django !== 'undefined' && typeof django.gettext !== 'undefined') {
return django.gettext(msgid)
export function gettext(msgid: string): string {
if (typeof django !== "undefined" && typeof django.gettext !== "undefined") {
return django.gettext(msgid);
}
return 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)
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
return plural;
}
export type I18nString = string | Record<string, string> | null | undefined
export type I18nString = string | Record<string, string> | null | undefined;
export function i18nstringLocalize (obj: I18nString): string {
export function i18nstringLocalize(obj: I18nString): string {
// external
return i18nstring_localize(obj)
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.'),
'checkinlist.switch': gettext('Switch check-in list'),
'results.headline': gettext('Search results'),
'results.none': gettext('No tickets found'),
'check.headline': gettext('Result'),
'check.attention': gettext('This ticket requires special attention'),
'scantype.switch': gettext('Switch direction'),
'scantype.entry': gettext('Entry'),
'scantype.exit': gettext('Exit'),
'input.placeholder': gettext('Scan a ticket or search and press return…'),
'pagination.next': gettext('Load more'),
'status.p': gettext('Valid'),
'status.n': gettext('Unpaid'),
'status.c': gettext('Canceled'),
'status.e': gettext('Canceled'),
'status.pending_valid': gettext('Confirmed'),
'status.require_approval': gettext('Approval pending'),
'status.redeemed': gettext('Redeemed'),
'modal.cancel': gettext('Cancel'),
'modal.continue': gettext('Continue'),
'modal.unpaid.head': gettext('Ticket not paid'),
'modal.unpaid.text': gettext('This ticket is not yet paid. Do you want to continue anyways?'),
'modal.questions': gettext('Additional information required'),
'result.ok': gettext('Valid ticket'),
'result.exit': gettext('Exit recorded'),
'result.already_redeemed': gettext('Ticket already used'),
'result.questions': gettext('Information required'),
'result.invalid': gettext('Unknown ticket'),
'result.product': gettext('Ticket type not allowed here'),
'result.unpaid': gettext('Ticket not paid'),
'result.rules': gettext('Entry not allowed'),
'result.revoked': gettext('Ticket code revoked/changed'),
'result.blocked': gettext('Ticket blocked'),
'result.invalid_time': gettext('Ticket not valid at this time'),
'result.canceled': gettext('Order canceled'),
'result.ambiguous': gettext('Ticket code is ambiguous on list'),
'result.unapproved': gettext('Order not approved'),
'status.checkin': gettext('Checked-in Tickets'),
'status.position': gettext('Valid Tickets'),
'status.inside': gettext('Currently inside'),
yes: gettext('Yes'),
no: gettext('No'),
}
"checkinlist.select": gettext("Select a check-in list"),
"checkinlist.none": gettext("No active check-in lists found."),
"checkinlist.switch": gettext("Switch check-in list"),
"results.headline": gettext("Search results"),
"results.none": gettext("No tickets found"),
"check.headline": gettext("Result"),
"check.attention": gettext("This ticket requires special attention"),
"scantype.switch": gettext("Switch direction"),
"scantype.entry": gettext("Entry"),
"scantype.exit": gettext("Exit"),
"input.placeholder": gettext("Scan a ticket or search and press return…"),
"pagination.next": gettext("Load more"),
"status.p": gettext("Valid"),
"status.n": gettext("Unpaid"),
"status.c": gettext("Canceled"),
"status.e": gettext("Canceled"),
"status.pending_valid": gettext("Confirmed"),
"status.require_approval": gettext("Approval pending"),
"status.redeemed": gettext("Redeemed"),
"modal.cancel": gettext("Cancel"),
"modal.continue": gettext("Continue"),
"modal.unpaid.head": gettext("Ticket not paid"),
"modal.unpaid.text": gettext(
"This ticket is not yet paid. Do you want to continue anyways?",
),
"modal.questions": gettext("Additional information required"),
"result.ok": gettext("Valid ticket"),
"result.exit": gettext("Exit recorded"),
"result.already_redeemed": gettext("Ticket already used"),
"result.questions": gettext("Information required"),
"result.invalid": gettext("Unknown ticket"),
"result.product": gettext("Ticket type not allowed here"),
"result.unpaid": gettext("Ticket not paid"),
"result.rules": gettext("Entry not allowed"),
"result.revoked": gettext("Ticket code revoked/changed"),
"result.blocked": gettext("Ticket blocked"),
"result.invalid_time": gettext("Ticket not valid at this time"),
"result.canceled": gettext("Order canceled"),
"result.ambiguous": gettext("Ticket code is ambiguous on list"),
"result.unapproved": gettext("Order not approved"),
"status.checkin": gettext("Checked-in Tickets"),
"status.position": gettext("Valid Tickets"),
"status.inside": gettext("Currently inside"),
yes: gettext("Yes"),
no: gettext("No"),
};
export interface SubEvent {
name: Record<string, string>
date_from: string
name: Record<string, string>;
date_from: string;
}
export function formatSubevent (subevent: SubEvent | null | undefined): string {
if (!subevent) return ''
const name = i18nstringLocalize(subevent.name)
const date = moment.utc(subevent.date_from).tz(timezone).format(datetimeFormat)
return `${name} · ${date}`
export function formatSubevent(subevent: SubEvent | null | undefined): string {
if (!subevent) return "";
const name = i18nstringLocalize(subevent.name);
const date = moment
.utc(subevent.date_from)
.tz(timezone)
.format(datetimeFormat);
return `${name} · ${date}`;
}
export interface Question {
type: string
type: string;
}
export function formatAnswer (value: string, question: Question): string {
if (question.type === 'B' && value === 'True') {
return STRINGS['yes']
} else if (question.type === 'B' && value === 'False') {
return STRINGS['no']
} else if (question.type === 'W' && value) {
return moment(value).tz(timezone).format('L LT')
} else if (question.type === 'D' && value) {
return moment(value).format('L')
export function formatAnswer(value: string, question: Question): string {
if (question.type === "B" && value === "True") {
return STRINGS["yes"];
} else if (question.type === "B" && value === "False") {
return STRINGS["no"];
} else if (question.type === "W" && value) {
return moment(value).tz(timezone).format("L LT");
} else if (question.type === "D" && value) {
return moment(value).format("L");
}
return value
return value;
}
@@ -1,17 +1,17 @@
import { createApp } from 'vue'
import { createApp } from "vue";
// import './scss/main.scss'
import App from './components/app.vue'
import App from "./components/app.vue";
const mountEl = document.querySelector<HTMLElement>('#app')!
const mountEl = document.querySelector<HTMLElement>("#app")!;
const app = createApp(App, mountEl.dataset)
app.mount('#app')
const app = createApp(App, mountEl.dataset);
app.mount("#app");
app.config.errorHandler = (error, _vm, info) => {
// vue fatals on errors by default, which is a weird choice
// https://github.com/vuejs/core/issues/3525
// https://github.com/vuejs/router/discussions/2435
console.error('[VUE]', info, error)
}
console.error("[VUE]", info, error);
};
+1 -1
View File
@@ -267,7 +267,7 @@ class CustomerStep(CartMixin, TemplateFlowStep):
else None
),
prefix='login',
request=self.request,
request=self.request.event,
)
for field in f.fields.values():
field._show_required = field.required
@@ -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" %}
@@ -44,6 +44,7 @@
{% else %}
<meta property="og:url" content="{% abseventurl request.event "presale:event.index" %}" />
{% endif %}
<script type="text/javascript" src="{% static "pretixpresale/js/csrfcookieretry.js" %}"></script>
{% endblock %}
{% block content %}
@@ -23,6 +23,10 @@
{% endif %}
{% trans "Order details" %}
{% endblock %}
{% block custom_header %}
{{ block.super }}
<script type="text/javascript" src="{% static "pretixpresale/js/csrfcookieretry.js" %}"></script>
{% endblock %}
{% block content %}
{% if "thanks" in request.GET or "paid" in request.GET %}
<div class="thank-you">
@@ -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">
@@ -23,5 +23,4 @@
<script type="text/javascript" src="{% static "pretixbase/js/addressform.js" %}"></script>
<script type="text/javascript" src="{% static "pretixbase/js/deanonymize_email.js" %}"></script>
<script type="text/javascript" src="{% static "pretixbase/js/errors.js" %}"></script>
<script type="text/javascript" src="{% static "pretixbase/js/csrfcookieretry.js" %}"></script>
{% endcompress %}
+3 -3
View File
@@ -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'),
+2 -2
View File
@@ -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
+1 -1
View File
@@ -83,7 +83,7 @@ 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:
utm_params = {k: v for k, v in request.GET.items() if k.startswith("utm_") or k == "gclid" or k == "_gl"}
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', ''))
+6 -4
View File
@@ -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]
)
+1 -11
View File
@@ -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,76 +0,0 @@
document.addEventListener('DOMContentLoaded', () => {
const COOKIE_NAME = window.location.protocol === 'https:' ? '__Host-pretix_csrftoken' : 'pretix_csrftoken'
const RELOAD_FLAG = 'csrfReloadPerformed'
const REASON_PARAM = 'csrf_reload'
const CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
// reimplementation of CSRFMiddlewares _unmask_cipher_token()
const unmask = (token) => {
if (!token || token.length !== 64) return token || null
let secret = ''
for (let i = 0; i < 32; i++) {
const m = CHARS.indexOf(token[i])
const c = CHARS.indexOf(token[32 + i])
if (m < 0 || c < 0) return null
secret += CHARS[(c - m + CHARS.length) % CHARS.length]
}
return secret
}
const url = new URL(location.href)
// remove reason after reload to avoid re-reports
if (url.searchParams.has(REASON_PARAM)) {
url.searchParams.delete(REASON_PARAM)
history.replaceState(history.state, '', url)
}
const readCookieSecrets = () => document.cookie
.split('; ')
.filter((c) => c.startsWith(COOKIE_NAME + '='))
.map((c) => unmask(c.slice(COOKIE_NAME.length + 1)))
// a deletion only hits the variant whose attributes it matches
const EXPIRE = `${COOKIE_NAME}=; Path=/; Secure; Max-Age=0`
const deleteUnpartitioned = () => {
document.cookie = EXPIRE
}
const deletePartitioned = () => {
document.cookie = `${EXPIRE}; Partitioned`
}
const field = document.querySelector('input[name="csrfmiddlewaretoken"]')
const pageSecret = field ? unmask(field.value) : null
// bail if there is no pageSecret
if (!pageSecret) return
const check = (secrets) => {
if (secrets.length === 0) return 'no_cookie'
if (secrets.length > 1) return 'duplicate_cookie'
if (!secrets[0]) return 'invalid_cookie'
if (pageSecret !== null && pageSecret !== secrets[0]) return 'mismatch'
return null
}
let cookieSecrets = readCookieSecrets()
let reason = check(cookieSecrets)
if (reason === 'duplicate_cookie') {
// drop the unpartitioned cookie, keep the partitioned one, maybe this fixes all issues
deleteUnpartitioned()
cookieSecrets = readCookieSecrets()
if (check(cookieSecrets)) {
reason = 'duplicate_cookie'
} else {
reason = null
}
}
if (reason && !sessionStorage.getItem(RELOAD_FLAG)) {
sessionStorage.setItem(RELOAD_FLAG, '1')
deleteUnpartitioned()
deletePartitioned()
url.searchParams.set(REASON_PARAM, reason)
location.href = url.href
} else if (!reason && sessionStorage.getItem(RELOAD_FLAG)) {
sessionStorage.removeItem(RELOAD_FLAG)
}
})
@@ -1,72 +1,81 @@
<script setup lang="ts">
import { computed } from 'vue'
import { rules as rawRules, allItems, activeItems, allProducts, limitProducts } from './django-interop'
import { convertToDNF } from './jsonlogic-boolalg'
import { computed } from "vue";
import {
rules as rawRules,
allItems,
activeItems,
allProducts,
limitProducts,
} from "./django-interop";
import { convertToDNF } from "./jsonlogic-boolalg";
import RulesEditor from './checkin-rules-editor.vue'
import RulesVisualization from './checkin-rules-visualization.vue'
import RulesEditor from "./checkin-rules-editor.vue";
import RulesVisualization from "./checkin-rules-visualization.vue";
const gettext = (window as any).gettext
const gettext = (window as any).gettext;
const missingItems = computed(() => {
// This computed variable contains list of item or variation names that
// a) Are allowed on the checkin list according to all_products or include_products
// b) Are not matched by ANY logical branch of the rule.
// The list will be empty if there is a "catch-all" rule.
let productsSeen = {}
let variationsSeen = {}
let rules = convertToDNF(rawRules.value)
let branchWithoutProductFilter = false
let productsSeen = {};
let variationsSeen = {};
let rules = convertToDNF(rawRules.value);
let branchWithoutProductFilter = false;
if (!rules.or) {
rules = { or: [rules] }
rules = { or: [rules] };
}
for (let part of rules.or) {
if (!part.and) {
part = { and: [part] }
part = { and: [part] };
}
let thisBranchWithoutProductFilter = true
let thisBranchWithoutProductFilter = true;
for (let subpart of part.and) {
if (subpart.inList) {
if (subpart.inList[0].var === 'product' && subpart.inList[1]) {
thisBranchWithoutProductFilter = false
if (subpart.inList[0].var === "product" && subpart.inList[1]) {
thisBranchWithoutProductFilter = false;
for (let listentry of subpart.inList[1].objectList) {
productsSeen[parseInt(listentry.lookup[1])] = true
productsSeen[parseInt(listentry.lookup[1])] = true;
}
} else if (subpart.inList[0].var === 'variation' && subpart.inList[1]) {
thisBranchWithoutProductFilter = false
} else if (subpart.inList[0].var === "variation" && subpart.inList[1]) {
thisBranchWithoutProductFilter = false;
for (let listentry_ of subpart.inList[1].objectList) {
variationsSeen[parseInt(listentry_.lookup[1])] = true
variationsSeen[parseInt(listentry_.lookup[1])] = true;
}
}
}
}
if (thisBranchWithoutProductFilter) {
branchWithoutProductFilter = true
break
branchWithoutProductFilter = true;
break;
}
}
if (branchWithoutProductFilter || (!Object.keys(productsSeen).length && !Object.keys(variationsSeen).length)) {
if (
branchWithoutProductFilter ||
(!Object.keys(productsSeen).length && !Object.keys(variationsSeen).length)
) {
// At least one branch with no product filters at all – that's fine.
return []
return [];
}
let missing = []
let missing = [];
for (const item of activeItems.value) {
if (productsSeen[item.id]) continue
if (!allProducts.value && !limitProducts.value.includes(item.id)) continue
if (productsSeen[item.id]) continue;
if (!allProducts.value && !limitProducts.value.includes(item.id)) continue;
if (item.variations.length > 0) {
for (let variation of item.variations) {
if (variationsSeen[variation.id]) continue
missing.push(item.name + ' – ' + variation.name)
if (variationsSeen[variation.id]) continue;
missing.push(item.name + " – " + variation.name);
}
} else {
missing.push(item.name)
missing.push(item.name);
}
}
return missing
})
return missing;
});
</script>
<template lang="pug">
#rules-editor.form-inline
@@ -98,5 +107,4 @@ const missingItems = computed(() => {
li(v-for="h in missingItems", :key="h") {{ h }}
p {{ gettext("Please double-check if this was intentional.") }}
</template>
<style lang="stylus">
</style>
<style lang="stylus"></style>
@@ -1,230 +1,258 @@
<script setup lang="ts">
/* eslint-disable vue/no-mutating-props */
import { computed } from 'vue'
import { TEXTS, VARS, TYPEOPS } from './constants'
import { productSelectURL, variationSelectURL, gateSelectURL } from './django-interop'
import LookupSelect2 from './lookup-select2.vue'
import Datetimefield from './datetimefield.vue'
import Timefield from './timefield.vue'
import { computed } from "vue";
import { TEXTS, VARS, TYPEOPS } from "./constants";
import {
productSelectURL,
variationSelectURL,
gateSelectURL,
} from "./django-interop";
import LookupSelect2 from "./lookup-select2.vue";
import Datetimefield from "./datetimefield.vue";
import Timefield from "./timefield.vue";
const props = defineProps<{
rule: any
level: number
index: number
}>()
rule: any;
level: number;
index: number;
}>();
const emit = defineEmits<{
remove: []
duplicate: []
}>()
remove: [];
duplicate: [];
}>();
const operator = computed(() => Object.keys(props.rule)[0])
const operands = computed(() => props.rule[operator.value])
const operator = computed(() => Object.keys(props.rule)[0]);
const operands = computed(() => props.rule[operator.value]);
const variable = computed(() => {
const op = operator.value
if (op === 'and' || op === 'or') {
return op
const op = operator.value;
if (op === "and" || op === "or") {
return op;
} else if (props.rule[op]?.[0]) {
if (props.rule[op][0]['entries_since']) return 'entries_since'
if (props.rule[op][0]['entries_before']) return 'entries_before'
if (props.rule[op][0]['entries_days_since']) return 'entries_days_since'
if (props.rule[op][0]['entries_days_before']) return 'entries_days_before'
return props.rule[op][0]['var']
if (props.rule[op][0]["entries_since"]) return "entries_since";
if (props.rule[op][0]["entries_before"]) return "entries_before";
if (props.rule[op][0]["entries_days_since"]) return "entries_days_since";
if (props.rule[op][0]["entries_days_before"]) return "entries_days_before";
return props.rule[op][0]["var"];
}
return null
})
return null;
});
const rightoperand = computed(() => {
const op = operator.value
if (op === 'and' || op === 'or') return null
return props.rule[op]?.[1] ?? null
})
const op = operator.value;
if (op === "and" || op === "or") return null;
return props.rule[op]?.[1] ?? null;
});
const classObject = computed(() => ({
'checkin-rule': true,
['checkin-rule-' + variable.value]: true
}))
"checkin-rule": true,
["checkin-rule-" + variable.value]: true,
}));
const vartype = computed(() => VARS[variable.value]?.type)
const vartype = computed(() => VARS[variable.value]?.type);
const timeType = computed(() => {
if (vartype.value === 'int_by_datetime') {
return props.rule[operator.value]?.[0]?.[variable.value]?.[0]?.buildTime?.[0]
if (vartype.value === "int_by_datetime") {
return props.rule[operator.value]?.[0]?.[variable.value]?.[0]
?.buildTime?.[0];
}
return rightoperand.value?.buildTime?.[0]
})
return rightoperand.value?.buildTime?.[0];
});
const timeTolerance = computed(() => {
const op = operator.value
if ((op === 'isBefore' || op === 'isAfter') && props.rule[op]?.[2] !== undefined) {
return props.rule[op][2]
const op = operator.value;
if (
(op === "isBefore" || op === "isAfter") &&
props.rule[op]?.[2] !== undefined
) {
return props.rule[op][2];
}
return null
})
return null;
});
const timeValue = computed(() => {
if (vartype.value === 'int_by_datetime') {
return props.rule[operator.value]?.[0]?.[variable.value]?.[0]?.buildTime?.[1]
if (vartype.value === "int_by_datetime") {
return props.rule[operator.value]?.[0]?.[variable.value]?.[0]
?.buildTime?.[1];
}
return rightoperand.value?.buildTime?.[1]
})
return rightoperand.value?.buildTime?.[1];
});
const cardinality = computed(() => TYPEOPS[vartype.value]?.[operator.value]?.cardinality)
const operators = computed(() => TYPEOPS[vartype.value])
const cardinality = computed(
() => TYPEOPS[vartype.value]?.[operator.value]?.cardinality,
);
const operators = computed(() => TYPEOPS[vartype.value]);
function setVariable (event: Event) {
const target = event.target as HTMLSelectElement
const currentOp = Object.keys(props.rule)[0]
let currentVal = props.rule[currentOp]
function setVariable(event: Event) {
const target = event.target as HTMLSelectElement;
const currentOp = Object.keys(props.rule)[0];
let currentVal = props.rule[currentOp];
if (target.value === 'and' || target.value === 'or') {
if (currentVal[0]?.var) currentVal = []
props.rule[target.value] = currentVal
delete props.rule[currentOp]
if (target.value === "and" || target.value === "or") {
if (currentVal[0]?.var) currentVal = [];
props.rule[target.value] = currentVal;
delete props.rule[currentOp];
} else {
if (currentVal !== 'and' && currentVal !== 'or' && currentVal[0] && VARS[target.value]?.type === vartype.value) {
if (vartype.value === 'int_by_datetime') {
const currentData = props.rule[currentOp][0][variable.value]
props.rule[currentOp][0] = { [target.value]: JSON.parse(JSON.stringify(currentData)) }
if (
currentVal !== "and" &&
currentVal !== "or" &&
currentVal[0] &&
VARS[target.value]?.type === vartype.value
) {
if (vartype.value === "int_by_datetime") {
const currentData = props.rule[currentOp][0][variable.value];
props.rule[currentOp][0] = {
[target.value]: JSON.parse(JSON.stringify(currentData)),
};
} else {
props.rule[currentOp][0].var = target.value
props.rule[currentOp][0].var = target.value;
}
} else if (VARS[target.value]?.type === 'int_by_datetime') {
delete props.rule[currentOp]
props.rule['!!'] = [{ [target.value]: [{ buildTime: [null, null] }] }]
} else if (VARS[target.value]?.type === "int_by_datetime") {
delete props.rule[currentOp];
props.rule["!!"] = [{ [target.value]: [{ buildTime: [null, null] }] }];
} else {
delete props.rule[currentOp]
props.rule['!!'] = [{ var: target.value }]
delete props.rule[currentOp];
props.rule["!!"] = [{ var: target.value }];
}
}
}
function setOperator (event: Event) {
const target = event.target as HTMLSelectElement
const currentOp = Object.keys(props.rule)[0]
const currentVal = props.rule[currentOp]
delete props.rule[currentOp]
props.rule[target.value] = currentVal
function setOperator(event: Event) {
const target = event.target as HTMLSelectElement;
const currentOp = Object.keys(props.rule)[0];
const currentVal = props.rule[currentOp];
delete props.rule[currentOp];
props.rule[target.value] = currentVal;
}
function setRightOperandNumber (event: Event) {
const val = parseInt((event.target as HTMLInputElement).value)
function setRightOperandNumber(event: Event) {
const val = parseInt((event.target as HTMLInputElement).value);
if (props.rule[operator.value].length === 1) {
props.rule[operator.value].push(val)
props.rule[operator.value].push(val);
} else {
props.rule[operator.value][1] = val
props.rule[operator.value][1] = val;
}
}
function setTimeTolerance (event: Event) {
const val = parseInt((event.target as HTMLInputElement).value)
function setTimeTolerance(event: Event) {
const val = parseInt((event.target as HTMLInputElement).value);
if (props.rule[operator.value].length === 2) {
props.rule[operator.value].push(val)
props.rule[operator.value].push(val);
} else {
props.rule[operator.value][2] = val
props.rule[operator.value][2] = val;
}
}
function setTimeType (event: Event) {
const val = (event.target as HTMLSelectElement).value
const time = { buildTime: [val] }
if (vartype.value === 'int_by_datetime') {
props.rule[operator.value][0][variable.value][0] = time
function setTimeType(event: Event) {
const val = (event.target as HTMLSelectElement).value;
const time = { buildTime: [val] };
if (vartype.value === "int_by_datetime") {
props.rule[operator.value][0][variable.value][0] = time;
} else {
if (props.rule[operator.value].length === 1) {
props.rule[operator.value].push(time)
props.rule[operator.value].push(time);
} else {
props.rule[operator.value][1] = time
props.rule[operator.value][1] = time;
}
if (val === 'custom') {
props.rule[operator.value][2] = 0
if (val === "custom") {
props.rule[operator.value][2] = 0;
}
}
}
function setTimeValue (val: string) {
if (vartype.value === 'int_by_datetime') {
props.rule[operator.value][0][variable.value][0]['buildTime'][1] = val
function setTimeValue(val: string) {
if (vartype.value === "int_by_datetime") {
props.rule[operator.value][0][variable.value][0]["buildTime"][1] = val;
} else {
props.rule[operator.value][1]['buildTime'][1] = val
props.rule[operator.value][1]["buildTime"][1] = val;
}
}
function setRightOperandProductList (val: { id: any; text: string }[]) {
const products = { objectList: val.map(item => ({ lookup: ['product', item.id, item.text] })) }
function setRightOperandProductList(val: { id: any; text: string }[]) {
const products = {
objectList: val.map((item) => ({
lookup: ["product", item.id, item.text],
})),
};
if (props.rule[operator.value].length === 1) {
props.rule[operator.value].push(products)
props.rule[operator.value].push(products);
} else {
props.rule[operator.value][1] = products
props.rule[operator.value][1] = products;
}
}
function setRightOperandVariationList (val: { id: any; text: string }[]) {
const products = { objectList: val.map(item => ({ lookup: ['variation', item.id, item.text] })) }
function setRightOperandVariationList(val: { id: any; text: string }[]) {
const products = {
objectList: val.map((item) => ({
lookup: ["variation", item.id, item.text],
})),
};
if (props.rule[operator.value].length === 1) {
props.rule[operator.value].push(products)
props.rule[operator.value].push(products);
} else {
props.rule[operator.value][1] = products
props.rule[operator.value][1] = products;
}
}
function setRightOperandGateList (val: { id: any; text: string }[]) {
const products = { objectList: val.map(item => ({ lookup: ['gate', item.id, item.text] })) }
function setRightOperandGateList(val: { id: any; text: string }[]) {
const products = {
objectList: val.map((item) => ({ lookup: ["gate", item.id, item.text] })),
};
if (props.rule[operator.value].length === 1) {
props.rule[operator.value].push(products)
props.rule[operator.value].push(products);
} else {
props.rule[operator.value][1] = products
props.rule[operator.value][1] = products;
}
}
function setRightOperandEnum (event: Event) {
const val = (event.target as HTMLSelectElement).value
function setRightOperandEnum(event: Event) {
const val = (event.target as HTMLSelectElement).value;
if (props.rule[operator.value].length === 1) {
props.rule[operator.value].push(val)
props.rule[operator.value].push(val);
} else {
props.rule[operator.value][1] = val
props.rule[operator.value][1] = val;
}
}
function addOperand () {
props.rule[operator.value].push({ '': [] })
function addOperand() {
props.rule[operator.value].push({ "": [] });
}
function wrapWithOR () {
const r = JSON.parse(JSON.stringify(props.rule))
delete props.rule[operator.value]
props.rule.or = [r]
function wrapWithOR() {
const r = JSON.parse(JSON.stringify(props.rule));
delete props.rule[operator.value];
props.rule.or = [r];
}
function wrapWithAND () {
const r = JSON.parse(JSON.stringify(props.rule))
delete props.rule[operator.value]
props.rule.and = [r]
function wrapWithAND() {
const r = JSON.parse(JSON.stringify(props.rule));
delete props.rule[operator.value];
props.rule.and = [r];
}
function cutOut () {
const cop = Object.keys(operands.value[0])[0]
const r = operands.value[0][cop]
delete props.rule[operator.value]
props.rule[cop] = r
function cutOut() {
const cop = Object.keys(operands.value[0])[0];
const r = operands.value[0][cop];
delete props.rule[operator.value];
props.rule[cop] = r;
}
function remove () {
emit('remove')
function remove() {
emit("remove");
}
function duplicate () {
emit('duplicate')
function duplicate() {
emit("duplicate");
}
function removeChild (index: number) {
props.rule[operator.value].splice(index, 1)
function removeChild(index: number) {
props.rule[operator.value].splice(index, 1);
}
function duplicateChild (index: number) {
const r = JSON.parse(JSON.stringify(props.rule[operator.value][index]))
props.rule[operator.value].splice(index, 0, r)
function duplicateChild(index: number) {
const r = JSON.parse(JSON.stringify(props.rule[operator.value][index]));
props.rule[operator.value].splice(index, 0, r);
}
</script>
<template lang="pug">
@@ -1,13 +1,13 @@
<script setup lang="ts">
import { computed } from 'vue'
import { TEXTS } from './constants'
import { rules } from './django-interop'
import CheckinRule from './checkin-rule.vue'
import { computed } from "vue";
import { TEXTS } from "./constants";
import { rules } from "./django-interop";
import CheckinRule from "./checkin-rule.vue";
const hasRules = computed(() => !!Object.keys(rules.value).length)
const hasRules = computed(() => !!Object.keys(rules.value).length);
function addRule () {
rules.value.and = []
function addRule() {
rules.value.and = [];
}
</script>
<template lang="pug">
@@ -1,36 +1,36 @@
<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted, nextTick } from 'vue'
import { rules } from './django-interop'
import VizNode from './viz-node.vue'
import { ref, computed, watch, onMounted, onUnmounted, nextTick } from "vue";
import { rules } from "./django-interop";
import VizNode from "./viz-node.vue";
declare const d3: any
declare const d3: any;
const svg = ref<SVGSVGElement | null>(null)
const maximized = ref(false)
const zoom = ref<any>(null)
const defaultScale = ref(1)
const zoomTransform = ref(d3.zoomTransform({ k: 1, x: 0, y: 0 }))
const svg = ref<SVGSVGElement | null>(null);
const maximized = ref(false);
const zoom = ref<any>(null);
const defaultScale = ref(1);
const zoomTransform = ref(d3.zoomTransform({ k: 1, x: 0, y: 0 }));
const boxWidth = 300
const boxHeight = 62
const paddingX = 50
const marginX = 50
const marginY = 20
const boxWidth = 300;
const boxHeight = 62;
const paddingX = 50;
const marginX = 50;
const marginY = 20;
interface GraphNode {
rule: any
column: number
children: string[]
y?: number
parent?: GraphNode
rule: any;
column: number;
children: string[];
y?: number;
parent?: GraphNode;
}
interface Graph {
nodes_by_id: Record<string, GraphNode>
children: string[]
columns: number
height: number
y?: number
nodes_by_id: Record<string, GraphNode>;
children: string[];
columns: number;
height: number;
y?: number;
}
const graph = computed<Graph>(() => {
@@ -69,175 +69,198 @@ const graph = computed<Graph>(() => {
children: [],
columns: -1,
height: 1,
}
};
// Step 1: Start building the graph by finding all nodes and edges
let counter = 0
const _add_to_graph = (rule: any): [string[], string[]] => { // returns [heads, tails]
if (typeof rule !== 'object' || rule === null) {
const node_id = (counter++).toString()
let counter = 0;
const _add_to_graph = (rule: any): [string[], string[]] => {
// returns [heads, tails]
if (typeof rule !== "object" || rule === null) {
const node_id = (counter++).toString();
graphData.nodes_by_id[node_id] = {
rule: rule,
column: -1,
children: [],
}
return [[node_id], [node_id]]
};
return [[node_id], [node_id]];
}
const operator = Object.keys(rule)[0]
const operands = rule[operator]
const operator = Object.keys(rule)[0];
const operands = rule[operator];
if (operator === 'and') {
let children: string[] = []
let tails: string[] | null = null
operands.reverse()
if (operator === "and") {
let children: string[] = [];
let tails: string[] | null = null;
operands.reverse();
for (const operand of operands) {
const [new_children, new_tails] = _add_to_graph(operand)
const [new_children, new_tails] = _add_to_graph(operand);
for (const new_child of new_tails) {
graphData.nodes_by_id[new_child].children.push(...children)
graphData.nodes_by_id[new_child].children.push(...children);
for (const c of children) {
graphData.nodes_by_id[c].parent = graphData.nodes_by_id[new_child]
graphData.nodes_by_id[c].parent = graphData.nodes_by_id[new_child];
}
}
if (tails === null) {
tails = new_tails
tails = new_tails;
}
children = new_children
children = new_children;
}
return [children, tails!]
} else if (operator === 'or') {
const children: string[] = []
const tails: string[] = []
return [children, tails!];
} else if (operator === "or") {
const children: string[] = [];
const tails: string[] = [];
for (const operand of operands) {
const [new_children, new_tails] = _add_to_graph(operand)
children.push(...new_children)
tails.push(...new_tails)
const [new_children, new_tails] = _add_to_graph(operand);
children.push(...new_children);
tails.push(...new_tails);
}
return [children, tails]
return [children, tails];
} else {
const node_id = (counter++).toString()
const node_id = (counter++).toString();
graphData.nodes_by_id[node_id] = {
rule: rule,
column: -1,
children: [],
}
return [[node_id], [node_id]]
};
return [[node_id], [node_id]];
}
}
graphData.children = _add_to_graph(JSON.parse(JSON.stringify(rules.value)))[0]
};
graphData.children = _add_to_graph(
JSON.parse(JSON.stringify(rules.value)),
)[0];
// Step 2: We compute the "column" of every node, which is the maximum number of hops required to reach the
// node from the root node
const _set_column_to_min = (nodes: GraphNode[], mincol: number) => {
for (const node of nodes) {
if (mincol > node.column) {
node.column = mincol
graphData.columns = Math.max(mincol + 1, graphData.columns)
_set_column_to_min(node.children.map(nid => graphData.nodes_by_id[nid]), mincol + 1)
node.column = mincol;
graphData.columns = Math.max(mincol + 1, graphData.columns);
_set_column_to_min(
node.children.map((nid) => graphData.nodes_by_id[nid]),
mincol + 1,
);
}
}
}
_set_column_to_min(graphData.children.map(nid => graphData.nodes_by_id[nid]), 0)
};
_set_column_to_min(
graphData.children.map((nid) => graphData.nodes_by_id[nid]),
0,
);
// Step 3: Align each node on a grid. The x position is already given by the column computed above, but we still
// need the y position. This part of the algorithm is opinionated and probably not yet the nicest solution we
// can use!
const _set_y = (node: Graph | GraphNode, offset: number): number => {
if (typeof node.y === 'undefined') {
if (typeof node.y === "undefined") {
// We only take the first value we found for each node
node.y = offset
node.y = offset;
}
let used = 0
let used = 0;
for (const cid of node.children) {
used += Math.max(0, _set_y(graphData.nodes_by_id[cid], offset + used) - 1)
used++
used += Math.max(
0,
_set_y(graphData.nodes_by_id[cid], offset + used) - 1,
);
used++;
}
return used
}
_set_y(graphData, 0)
return used;
};
_set_y(graphData, 0);
// Step 4: Compute the "height" of the graph by looking at the node with the highest y value
graphData.height = 1
graphData.height = 1;
for (const node of [...Object.values(graphData.nodes_by_id)]) {
graphData.height = Math.max(graphData.height, (node.y ?? 0) + 1)
graphData.height = Math.max(graphData.height, (node.y ?? 0) + 1);
}
return graphData
})
return graphData;
});
const contentWidth = computed(() => {
return graph.value.columns * (boxWidth + marginX) + 2 * paddingX
})
return graph.value.columns * (boxWidth + marginX) + 2 * paddingX;
});
const contentHeight = computed(() => {
return graph.value.height * (boxHeight + marginY)
})
return graph.value.height * (boxHeight + marginY);
});
const viewBox = computed(() => {
return `0 0 ${contentWidth.value} ${contentHeight.value}`
})
return `0 0 ${contentWidth.value} ${contentHeight.value}`;
});
function createZoom () {
if (!svg.value) return
function createZoom() {
if (!svg.value) return;
const viewportHeight = svg.value.clientHeight
const viewportWidth = svg.value.clientWidth
defaultScale.value = 1
const viewportHeight = svg.value.clientHeight;
const viewportWidth = svg.value.clientWidth;
defaultScale.value = 1;
zoom.value = d3
.zoom()
.scaleExtent([Math.min(defaultScale.value * 0.5, 1), Math.max(5, contentHeight.value / viewportHeight, contentWidth.value / viewportWidth)])
.extent([[0, 0], [viewportWidth, viewportHeight]])
.scaleExtent([
Math.min(defaultScale.value * 0.5, 1),
Math.max(
5,
contentHeight.value / viewportHeight,
contentWidth.value / viewportWidth,
),
])
.extent([
[0, 0],
[viewportWidth, viewportHeight],
])
.filter((event: any) => {
const wheeled = event.type === 'wheel'
const mouseDrag
= event.type === 'mousedown'
|| event.type === 'mouseup'
|| event.type === 'mousemove'
const touch
= event.type === 'touchstart'
|| event.type === 'touchmove'
|| event.type === 'touchstop'
return (wheeled || mouseDrag || touch) && maximized.value
const wheeled = event.type === "wheel";
const mouseDrag =
event.type === "mousedown" ||
event.type === "mouseup" ||
event.type === "mousemove";
const touch =
event.type === "touchstart" ||
event.type === "touchmove" ||
event.type === "touchstop";
return (wheeled || mouseDrag || touch) && maximized.value;
})
.wheelDelta((event: any) => {
// In contrast to default implementation, do not use a factor 10 if ctrl is pressed
return -event.deltaY * (event.deltaMode === 1 ? 0.05 : event.deltaMode ? 1 : 0.002)
})
.on('zoom', (event: any) => {
zoomTransform.value = event.transform
return (
-event.deltaY *
(event.deltaMode === 1 ? 0.05 : event.deltaMode ? 1 : 0.002)
);
})
.on("zoom", (event: any) => {
zoomTransform.value = event.transform;
});
const initTransform = d3.zoomIdentity
.scale(defaultScale.value)
.translate(0, 0)
zoomTransform.value = initTransform
.translate(0, 0);
zoomTransform.value = initTransform;
// This sets correct d3 internal state for the initial centering
d3.select(svg.value)
.call(zoom.value.transform, initTransform)
d3.select(svg.value).call(zoom.value.transform, initTransform);
const svgSelection = d3.select(svg.value).call(zoom.value)
svgSelection.on('touchmove.zoom', null)
const svgSelection = d3.select(svg.value).call(zoom.value);
svgSelection.on("touchmove.zoom", null);
// TODO touch support
}
watch(maximized, () => {
nextTick(() => {
createZoom()
})
})
createZoom();
});
});
onMounted(() => {
createZoom()
window.addEventListener('resize', createZoom)
})
createZoom();
window.addEventListener("resize", createZoom);
});
onUnmounted(() => {
window.removeEventListener('resize', createZoom)
})
window.removeEventListener("resize", createZoom);
});
</script>
<template lang="pug">
div(:class="'checkin-rules-visualization ' + (maximized ? 'maximized' : '')")
@@ -1,20 +1,20 @@
/* global gettext, pgettext */
export const TEXTS = {
and: gettext('All of the conditions below (AND)'),
or: gettext('At least one of the conditions below (OR)'),
date_from: gettext('Event start'),
date_to: gettext('Event end'),
date_admission: gettext('Event admission'),
date_custom: gettext('custom date and time'),
date_customtime: gettext('custom time'),
date_tolerance: gettext('Tolerance (minutes)'),
condition_add: gettext('Add condition'),
minutes: gettext('minutes'),
duplicate: gettext('Duplicate'),
status_present: pgettext('entry_status', 'present'),
status_absent: pgettext('entry_status', 'absent'),
}
and: gettext("All of the conditions below (AND)"),
or: gettext("At least one of the conditions below (OR)"),
date_from: gettext("Event start"),
date_to: gettext("Event end"),
date_admission: gettext("Event admission"),
date_custom: gettext("custom date and time"),
date_customtime: gettext("custom time"),
date_tolerance: gettext("Tolerance (minutes)"),
condition_add: gettext("Add condition"),
minutes: gettext("minutes"),
duplicate: gettext("Duplicate"),
status_present: pgettext("entry_status", "present"),
status_absent: pgettext("entry_status", "absent"),
};
export const TYPEOPS = {
// Every change to our supported JSON logic must be done
@@ -26,173 +26,173 @@ export const TYPEOPS = {
// * in pretixscan-ios
product: {
inList: {
label: gettext('is one of'),
label: gettext("is one of"),
cardinality: 2,
}
},
},
variation: {
inList: {
label: gettext('is one of'),
label: gettext("is one of"),
cardinality: 2,
}
},
},
gate: {
inList: {
label: gettext('is one of'),
label: gettext("is one of"),
cardinality: 2,
}
},
},
datetime: {
isBefore: {
label: gettext('is before'),
label: gettext("is before"),
cardinality: 2,
},
isAfter: {
label: gettext('is after'),
label: gettext("is after"),
cardinality: 2,
},
},
enum_entry_status: {
'==': {
label: gettext('='),
"==": {
label: gettext("="),
cardinality: 2,
},
},
int_by_datetime: {
'<': {
label: '<',
"<": {
label: "<",
cardinality: 2,
},
'<=': {
label: '≤',
"<=": {
label: "≤",
cardinality: 2,
},
'>': {
label: '>',
">": {
label: ">",
cardinality: 2,
},
'>=': {
label: '≥',
">=": {
label: "≥",
cardinality: 2,
},
'==': {
label: '=',
"==": {
label: "=",
cardinality: 2,
},
'!=': {
label: '≠',
"!=": {
label: "≠",
cardinality: 2,
},
},
int: {
'<': {
label: '<',
"<": {
label: "<",
cardinality: 2,
},
'<=': {
label: '≤',
"<=": {
label: "≤",
cardinality: 2,
},
'>': {
label: '>',
">": {
label: ">",
cardinality: 2,
},
'>=': {
label: '≥',
">=": {
label: "≥",
cardinality: 2,
},
'==': {
label: '=',
"==": {
label: "=",
cardinality: 2,
},
'!=': {
label: '≠',
"!=": {
label: "≠",
cardinality: 2,
},
},
}
};
export const VARS = {
product: {
label: gettext('Product'),
type: 'product',
label: gettext("Product"),
type: "product",
},
variation: {
label: gettext('Product variation'),
type: 'variation',
label: gettext("Product variation"),
type: "variation",
},
gate: {
label: gettext('Gate'),
type: 'gate',
label: gettext("Gate"),
type: "gate",
},
now: {
label: gettext('Current date and time'),
type: 'datetime',
label: gettext("Current date and time"),
type: "datetime",
},
now_isoweekday: {
label: gettext('Current day of the week (1 = Monday, 7 = Sunday)'),
type: 'int',
label: gettext("Current day of the week (1 = Monday, 7 = Sunday)"),
type: "int",
},
entry_status: {
label: gettext('Current entry status'),
type: 'enum_entry_status',
label: gettext("Current entry status"),
type: "enum_entry_status",
},
entries_number: {
label: gettext('Number of previous entries'),
type: 'int',
label: gettext("Number of previous entries"),
type: "int",
},
entries_today: {
label: gettext('Number of previous entries since midnight'),
type: 'int',
label: gettext("Number of previous entries since midnight"),
type: "int",
},
entries_since: {
label: gettext('Number of previous entries since'),
type: 'int_by_datetime',
label: gettext("Number of previous entries since"),
type: "int_by_datetime",
},
entries_before: {
label: gettext('Number of previous entries before'),
type: 'int_by_datetime',
label: gettext("Number of previous entries before"),
type: "int_by_datetime",
},
entries_days: {
label: gettext('Number of days with a previous entry'),
type: 'int',
label: gettext("Number of days with a previous entry"),
type: "int",
},
entries_days_since: {
label: gettext('Number of days with a previous entry since'),
type: 'int_by_datetime',
label: gettext("Number of days with a previous entry since"),
type: "int_by_datetime",
},
entries_days_before: {
label: gettext('Number of days with a previous entry before'),
type: 'int_by_datetime',
label: gettext("Number of days with a previous entry before"),
type: "int_by_datetime",
},
minutes_since_last_entry: {
label: gettext('Minutes since last entry (-1 on first entry)'),
type: 'int',
label: gettext("Minutes since last entry (-1 on first entry)"),
type: "int",
},
minutes_since_first_entry: {
label: gettext('Minutes since first entry (-1 on first entry)'),
type: 'int',
label: gettext("Minutes since first entry (-1 on first entry)"),
type: "int",
},
}
};
export const DATETIME_OPTIONS = {
format: document.body.dataset.datetimeformat,
locale: document.body.dataset.datetimelocale,
useCurrent: false,
icons: {
time: 'fa fa-clock-o',
date: 'fa fa-calendar',
up: 'fa fa-chevron-up',
down: 'fa fa-chevron-down',
previous: 'fa fa-chevron-left',
next: 'fa fa-chevron-right',
today: 'fa fa-screenshot',
clear: 'fa fa-trash',
close: 'fa fa-remove'
}
}
time: "fa fa-clock-o",
date: "fa fa-calendar",
up: "fa fa-chevron-up",
down: "fa fa-chevron-down",
previous: "fa fa-chevron-left",
next: "fa fa-chevron-right",
today: "fa fa-screenshot",
clear: "fa fa-trash",
close: "fa fa-remove",
},
};
export const TIME_OPTIONS = {
...DATETIME_OPTIONS,
format: document.body.dataset.timeformat,
}
};
@@ -1,21 +1,24 @@
<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted } from 'vue'
import { DATETIME_OPTIONS } from './constants'
import { ref, watch, onMounted, onUnmounted } from "vue";
import { DATETIME_OPTIONS } from "./constants";
const props = defineProps<{
required?: boolean
value?: string
}>()
required?: boolean;
value?: string;
}>();
const emit = defineEmits<{
input: [value: string]
}>()
input: [value: string];
}>();
const input = ref<HTMLInputElement | null>(null)
const input = ref<HTMLInputElement | null>(null);
watch(() => props.value, (val) => {
$(input.value).data('DateTimePicker').date(moment(val))
})
watch(
() => props.value,
(val) => {
$(input.value).data("DateTimePicker").date(moment(val));
},
);
onMounted(() => {
$(input.value)
@@ -23,22 +26,22 @@ onMounted(() => {
...DATETIME_OPTIONS,
showClear: props.required,
})
.trigger('change')
.on('dp.change', function (this: HTMLElement) {
emit('input', $(this).data('DateTimePicker').date().toISOString())
})
.trigger("change")
.on("dp.change", function (this: HTMLElement) {
emit("input", $(this).data("DateTimePicker").date().toISOString());
});
if (!props.value) {
$(input.value).data('DateTimePicker').viewDate(moment().hour(0).minute(0).second(0).millisecond(0))
$(input.value)
.data("DateTimePicker")
.viewDate(moment().hour(0).minute(0).second(0).millisecond(0));
} else {
$(input.value).data('DateTimePicker').date(moment(props.value))
$(input.value).data("DateTimePicker").date(moment(props.value));
}
})
});
onUnmounted(() => {
$(input.value)
.off()
.datetimepicker('destroy')
})
$(input.value).off().datetimepicker("destroy");
});
</script>
<template lang="pug">
input.form-control(ref="input")
@@ -1,70 +1,95 @@
import { ref, watch } from 'vue'
import { ref, watch } from "vue";
export const allProducts = ref(false)
export const limitProducts = ref<number[]>([])
export const allProducts = ref(false);
export const limitProducts = ref<number[]>([]);
function updateProducts () {
allProducts.value = document.querySelector<HTMLInputElement>('#id_all_products')?.checked ?? false
limitProducts.value = Array.from(document.querySelectorAll<HTMLInputElement>('input[name=limit_products]:checked')).map(el => parseInt(el.value))
function updateProducts() {
allProducts.value =
document.querySelector<HTMLInputElement>("#id_all_products")?.checked ??
false;
limitProducts.value = Array.from(
document.querySelectorAll<HTMLInputElement>(
"input[name=limit_products]:checked",
),
).map((el) => parseInt(el.value));
}
// listen to change events for products
document.querySelectorAll('#id_all_products, input[name=limit_products]').forEach(el => el.addEventListener('change', updateProducts))
updateProducts()
document
.querySelectorAll("#id_all_products, input[name=limit_products]")
.forEach((el) => el.addEventListener("change", updateProducts));
updateProducts();
export const rules = ref<any>({})
export const rules = ref<any>({});
// grab rules from hidden input
const rulesInput = document.querySelector<HTMLInputElement>('#id_rules')
const rulesInput = document.querySelector<HTMLInputElement>("#id_rules");
if (rulesInput?.value) {
rules.value = JSON.parse(rulesInput.value) ?? {}
rules.value = JSON.parse(rulesInput.value) ?? {};
}
// sync back to hidden input
watch(rules, (newVal) => {
if (!rulesInput) return
rulesInput.value = JSON.stringify(newVal)
}, { deep: true })
watch(
rules,
(newVal) => {
if (!rulesInput) return;
rulesInput.value = JSON.stringify(newVal);
},
{ deep: true },
);
export const activeItems = ref<any[]>([])
export const allItems = ref<any[]>([])
export const activeItems = ref<any[]>([]);
export const allItems = ref<any[]>([]);
const itemsEl = document.querySelector('#items')
const itemsEl = document.querySelector("#items");
if (itemsEl?.textContent) {
allItems.value = JSON.parse(itemsEl.textContent || '[]')
activeItems.value = allItems.value.filter(item => item.active)
allItems.value = JSON.parse(itemsEl.textContent || "[]");
activeItems.value = allItems.value.filter((item) => item.active);
function checkForInvalidIds (validProducts: Record<string, string>, validVariations: Record<string, string>, rule: any) {
if (rule['and']) {
for (const child of rule['and'])
checkForInvalidIds(validProducts, validVariations, child)
} else if (rule['or']) {
for (const child of rule['or'])
checkForInvalidIds(validProducts, validVariations, child)
} else if (rule['inList'] && rule['inList'][0]['var'] === 'product') {
for (const item of rule['inList'][1]['objectList']) {
if (!validProducts[item['lookup'][1]])
item['lookup'][2] = '[' + gettext('Error: Product not found!') + ']'
else
item['lookup'][2] = validProducts[item['lookup'][1]]
function checkForInvalidIds(
validProducts: Record<string, string>,
validVariations: Record<string, string>,
rule: any,
) {
if (rule["and"]) {
for (const child of rule["and"])
checkForInvalidIds(validProducts, validVariations, child);
} else if (rule["or"]) {
for (const child of rule["or"])
checkForInvalidIds(validProducts, validVariations, child);
} else if (rule["inList"] && rule["inList"][0]["var"] === "product") {
for (const item of rule["inList"][1]["objectList"]) {
if (!validProducts[item["lookup"][1]])
item["lookup"][2] = "[" + gettext("Error: Product not found!") + "]";
else item["lookup"][2] = validProducts[item["lookup"][1]];
}
} else if (rule['inList'] && rule['inList'][0]['var'] === 'variation') {
for (const item of rule['inList'][1]['objectList']) {
if (!validVariations[item['lookup'][1]])
item['lookup'][2] = '[' + gettext('Error: Variation not found!') + ']'
else
item['lookup'][2] = validVariations[item['lookup'][1]]
} else if (rule["inList"] && rule["inList"][0]["var"] === "variation") {
for (const item of rule["inList"][1]["objectList"]) {
if (!validVariations[item["lookup"][1]])
item["lookup"][2] =
"[" + gettext("Error: Variation not found!") + "]";
else item["lookup"][2] = validVariations[item["lookup"][1]];
}
}
}
checkForInvalidIds(
Object.fromEntries(allItems.value.map(p => [p.id, p.name])),
Object.fromEntries(allItems.value.flatMap(p => p.variations?.map(v => [v.id, p.name + ' – ' + v.name]) ?? [])),
rules.value
)
Object.fromEntries(allItems.value.map((p) => [p.id, p.name])),
Object.fromEntries(
allItems.value.flatMap(
(p) => p.variations?.map((v) => [v.id, p.name + " – " + v.name]) ?? [],
),
),
rules.value,
);
}
export const productSelectURL = ref(document.querySelector('#product-select2')?.textContent)
export const variationSelectURL = ref(document.querySelector('#variations-select2')?.textContent)
export const gateSelectURL = ref(document.querySelector('#gates-select2')?.textContent)
export const productSelectURL = ref(
document.querySelector("#product-select2")?.textContent,
);
export const variationSelectURL = ref(
document.querySelector("#variations-select2")?.textContent,
);
export const gateSelectURL = ref(
document.querySelector("#gates-select2")?.textContent,
);
@@ -1,12 +1,12 @@
import { createApp } from 'vue'
import App from './App.vue'
import { createApp } from "vue";
import App from "./App.vue";
const app = createApp(App)
app.mount('#rules-editor')
const app = createApp(App);
app.mount("#rules-editor");
app.config.errorHandler = (error, _vm, info) => {
// vue fatals on errors by default, which is a weird choice
// https://github.com/vuejs/core/issues/3525
// https://github.com/vuejs/router/discussions/2435
console.error('[VUE]', info, error)
}
console.error("[VUE]", info, error);
};
@@ -1,93 +1,110 @@
export function convertToDNF (rules) {
export function convertToDNF(rules) {
// Converts a set of rules to disjunctive normal form, i.e. returns something of the form
// `(a AND b AND c) OR (a AND d AND f)`
// without further nesting.
if (typeof rules !== 'object' || Array.isArray(rules) || rules === null) {
return rules
if (typeof rules !== "object" || Array.isArray(rules) || rules === null) {
return rules;
}
function _distribute_or_over_and (r) {
let operator = Object.keys(r)[0]
let values = r[operator]
if (operator === 'and') {
let arg_to_distribute = null
let other_args = []
function _distribute_or_over_and(r) {
let operator = Object.keys(r)[0];
let values = r[operator];
if (operator === "and") {
let arg_to_distribute = null;
let other_args = [];
for (let arg of values) {
if (typeof arg === 'object' && !Array.isArray(arg) && typeof arg['or'] !== 'undefined' && arg_to_distribute === null) {
arg_to_distribute = arg
if (
typeof arg === "object" &&
!Array.isArray(arg) &&
typeof arg["or"] !== "undefined" &&
arg_to_distribute === null
) {
arg_to_distribute = arg;
} else {
other_args.push(arg)
other_args.push(arg);
}
}
if (arg_to_distribute === null) {
return r
return r;
}
let or_operands = []
for (let dval of arg_to_distribute['or']) {
or_operands.push({ and: other_args.concat([dval]) })
let or_operands = [];
for (let dval of arg_to_distribute["or"]) {
or_operands.push({ and: other_args.concat([dval]) });
}
return {
or: or_operands
}
or: or_operands,
};
} else if (!operator) {
return r
} else if (operator === '!' || operator === '!!' || operator === '?:' || operator === 'if') {
console.warn('Operator ' + operator + ' currently unsupported by convert_to_dnf')
return r
return r;
} else if (
operator === "!" ||
operator === "!!" ||
operator === "?:" ||
operator === "if"
) {
console.warn(
"Operator " + operator + " currently unsupported by convert_to_dnf",
);
return r;
} else {
return r
return r;
}
}
function _simplify_chained_operators (r) {
function _simplify_chained_operators(r) {
// Simplify `(a OR b) OR (c or d)` to `a OR b OR c OR d` and the same with `AND`
if (typeof r !== 'object' || Array.isArray(r)) {
return r
if (typeof r !== "object" || Array.isArray(r)) {
return r;
}
let operator = Object.keys(r)[0]
let values = r[operator]
if (operator !== 'or' && operator !== 'and') {
return r
let operator = Object.keys(r)[0];
let values = r[operator];
if (operator !== "or" && operator !== "and") {
return r;
}
let new_values = []
let new_values = [];
for (let v of values) {
if (typeof v !== 'object' || Array.isArray(v) || typeof v[operator] === 'undefined') {
new_values.push(v)
if (
typeof v !== "object" ||
Array.isArray(v) ||
typeof v[operator] === "undefined"
) {
new_values.push(v);
} else {
new_values.push(...v[operator])
new_values.push(...v[operator]);
}
}
let result = {}
result[operator] = new_values
return result
let result = {};
result[operator] = new_values;
return result;
}
// Run _distribute_or_over_and on until it no longer changes anything. Do so recursively
// for the full expression tree.
let old_rules = rules
let old_rules = rules;
while (true) {
rules = _distribute_or_over_and(rules)
let operator = Object.keys(rules)[0]
let values = rules[operator]
let no_list = false
rules = _distribute_or_over_and(rules);
let operator = Object.keys(rules)[0];
let values = rules[operator];
let no_list = false;
if (!Array.isArray(values)) {
values = [values]
no_list = true
values = [values];
no_list = true;
}
rules = {}
rules = {};
if (!no_list) {
rules[operator] = []
rules[operator] = [];
for (let v of values) {
rules[operator].push(convertToDNF(v))
rules[operator].push(convertToDNF(v));
}
} else {
rules[operator] = convertToDNF(values[0])
rules[operator] = convertToDNF(values[0]);
}
if (JSON.stringify(old_rules) === JSON.stringify(rules)) { // Let's hope this is good enough...
break
if (JSON.stringify(old_rules) === JSON.stringify(rules)) {
// Let's hope this is good enough...
break;
}
old_rules = rules
old_rules = rules;
}
rules = _simplify_chained_operators(rules)
return rules
rules = _simplify_chained_operators(rules);
return rules;
}
@@ -1,119 +1,141 @@
<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted } from 'vue'
import { ref, watch, onMounted, onUnmounted } from "vue";
declare const $: any
declare const $: any;
export interface ObjectListItem {
lookup: [string, number | string, string]
lookup: [string, number | string, string];
}
export interface ObjectList {
objectList: ObjectListItem[]
objectList: ObjectListItem[];
}
const props = defineProps<{
required?: boolean
value?: ObjectList
placeholder?: string
url?: string
multiple?: boolean
}>()
required?: boolean;
value?: ObjectList;
placeholder?: string;
url?: string;
multiple?: boolean;
}>();
const emit = defineEmits<{
input: [value: any[]]
}>()
input: [value: any[]];
}>();
const select = ref<HTMLSelectElement | null>(null)
const select = ref<HTMLSelectElement | null>(null);
function opts () {
function opts() {
return {
theme: 'bootstrap',
theme: "bootstrap",
delay: 100,
width: '100%',
width: "100%",
multiple: true,
allowClear: props.required,
language: $('body').attr('data-select2-locale'),
language: $("body").attr("data-select2-locale"),
ajax: {
url: props.url,
data: function (params: { term: string; page?: number }) {
return {
query: params.term,
page: params.page || 1
}
}
page: params.page || 1,
};
},
},
templateResult: function (res: { id?: string; text: string }) {
if (!res.id) {
return res.text
return res.text;
}
const $ret = $('<span>').append(
$('<span>').addClass('primary').append($('<div>').text(res.text).html())
)
return $ret
const $ret = $("<span>").append(
$("<span>")
.addClass("primary")
.append($("<div>").text(res.text).html()),
);
return $ret;
},
}
};
}
function build () {
function build() {
$(select.value)
.empty()
.select2(opts())
.val(props.value || '')
.trigger('change')
.on('change', function (this: HTMLElement) {
emit('input', $(this).select2('data'))
})
.val(props.value || "")
.trigger("change")
.on("change", function (this: HTMLElement) {
emit("input", $(this).select2("data"));
});
if (props.value) {
for (let i = 0; i < props.value.objectList.length; i++) {
const option = new Option(props.value.objectList[i].lookup[2], String(props.value.objectList[i].lookup[1]), true, true)
$(select.value).append(option)
const option = new Option(
props.value.objectList[i].lookup[2],
String(props.value.objectList[i].lookup[1]),
true,
true,
);
$(select.value).append(option);
}
}
$(select.value).trigger('change')
$(select.value).trigger("change");
}
watch(() => props.placeholder, () => {
$(select.value).select2('destroy')
build()
})
watch(
() => props.placeholder,
() => {
$(select.value).select2("destroy");
build();
},
);
watch(() => props.required, () => {
$(select.value).select2('destroy')
build()
})
watch(
() => props.required,
() => {
$(select.value).select2("destroy");
build();
},
);
watch(() => props.url, () => {
$(select.value).select2('destroy')
build()
})
watch(
() => props.url,
() => {
$(select.value).select2("destroy");
build();
},
);
watch(() => props.value, (newval, oldval) => {
if (JSON.stringify(newval) !== JSON.stringify(oldval)) {
$(select.value).empty()
if (newval) {
for (let i = 0; i < newval.objectList.length; i++) {
const option = new Option(newval.objectList[i].lookup[2], String(newval.objectList[i].lookup[1]), true, true)
$(select.value).append(option)
watch(
() => props.value,
(newval, oldval) => {
if (JSON.stringify(newval) !== JSON.stringify(oldval)) {
$(select.value).empty();
if (newval) {
for (let i = 0; i < newval.objectList.length; i++) {
const option = new Option(
newval.objectList[i].lookup[2],
String(newval.objectList[i].lookup[1]),
true,
true,
);
$(select.value).append(option);
}
}
$(select.value).trigger("change");
}
$(select.value).trigger('change')
}
})
},
);
let rawSelectEl: HTMLSelectElement | null = null
let rawSelectEl: HTMLSelectElement | null = null;
onMounted(() => {
rawSelectEl = select.value
build()
})
rawSelectEl = select.value;
build();
});
onUnmounted(() => {
if (!rawSelectEl) return
$(rawSelectEl)
.off()
.select2('destroy')
rawSelectEl = null
})
if (!rawSelectEl) return;
$(rawSelectEl).off().select2("destroy");
rawSelectEl = null;
});
</script>
<template lang="pug">
select(ref="select")
@@ -1,21 +1,24 @@
<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted } from 'vue'
import { TIME_OPTIONS } from './constants'
import { ref, watch, onMounted, onUnmounted } from "vue";
import { TIME_OPTIONS } from "./constants";
const props = defineProps<{
required?: boolean
value?: string
}>()
required?: boolean;
value?: string;
}>();
const emit = defineEmits<{
input: [value: string]
}>()
input: [value: string];
}>();
const input = ref<HTMLInputElement | null>(null)
const input = ref<HTMLInputElement | null>(null);
watch(() => props.value, (val) => {
$(input.value).data('DateTimePicker').date(val)
})
watch(
() => props.value,
(val) => {
$(input.value).data("DateTimePicker").date(val);
},
);
onMounted(() => {
$(input.value)
@@ -23,22 +26,22 @@ onMounted(() => {
...TIME_OPTIONS,
showClear: props.required,
})
.trigger('change')
.on('dp.change', function (this: HTMLElement) {
emit('input', $(this).data('DateTimePicker').date().format('HH:mm:ss'))
})
.trigger("change")
.on("dp.change", function (this: HTMLElement) {
emit("input", $(this).data("DateTimePicker").date().format("HH:mm:ss"));
});
if (!props.value) {
$(input.value).data('DateTimePicker').viewDate(moment().hour(0).minute(0).second(0).millisecond(0))
$(input.value)
.data("DateTimePicker")
.viewDate(moment().hour(0).minute(0).second(0).millisecond(0));
} else {
$(input.value).data('DateTimePicker').date(props.value)
$(input.value).data("DateTimePicker").date(props.value);
}
})
});
onUnmounted(() => {
$(input.value)
.off()
.datetimepicker('destroy')
})
$(input.value).off().datetimepicker("destroy");
});
</script>
<template lang="pug">
input.form-control(ref="input")
@@ -1,43 +1,54 @@
<script setup lang="ts">
import { computed } from 'vue'
import { TEXTS, VARS, TYPEOPS } from './constants'
import { computed } from "vue";
import { TEXTS, VARS, TYPEOPS } from "./constants";
declare const $: any
declare const moment: any
declare const $: any;
declare const moment: any;
interface GraphNode {
rule: any
column: number
children: string[]
y: number
parent?: GraphNode
rule: any;
column: number;
children: string[];
y: number;
parent?: GraphNode;
}
const props = defineProps<{
node: GraphNode
nodeid: string
children: GraphNode[]
boxWidth: number
boxHeight: number
marginX: number
marginY: number
paddingX: number
}>()
node: GraphNode;
nodeid: string;
children: GraphNode[];
boxWidth: number;
boxHeight: number;
marginX: number;
marginY: number;
paddingX: number;
}>();
const x = computed(() => {
return props.node.column * (props.boxWidth + props.marginX) + props.marginX / 2 + props.paddingX
})
return (
props.node.column * (props.boxWidth + props.marginX) +
props.marginX / 2 +
props.paddingX
);
});
const y = computed(() => {
return props.node.y * (props.boxHeight + props.marginY) + props.marginY / 2
})
return props.node.y * (props.boxHeight + props.marginY) + props.marginY / 2;
});
const edges = computed(() => {
const startX = x.value + props.boxWidth + 1
const startY = y.value + props.boxHeight / 2
const startX = x.value + props.boxWidth + 1;
const startY = y.value + props.boxHeight / 2;
return props.children.map((c) => {
const endX = (c.column * (props.boxWidth + props.marginX) + props.marginX / 2 + props.paddingX) - 1
const endY = (c.y * (props.boxHeight + props.marginY) + props.marginY / 2) + props.boxHeight / 2
const endX =
c.column * (props.boxWidth + props.marginX) +
props.marginX / 2 +
props.paddingX -
1;
const endY =
c.y * (props.boxHeight + props.marginY) +
props.marginY / 2 +
props.boxHeight / 2;
return `
M ${startX} ${startY}
@@ -45,25 +56,25 @@ const edges = computed(() => {
C ${endX - 25} ${startY} ${endX - 25} ${startY} ${endX - 25} ${startY + 25 * Math.sign(endY - startY)}
L ${endX - 25} ${endY - 25 * Math.sign(endY - startY)}
C ${endX - 25} ${endY} ${endX - 25} ${endY} ${endX} ${endY}
`
})
})
`;
});
});
const checkEdge = computed(() => {
const startX = x.value + props.boxWidth + 1
const startY = y.value + props.boxHeight / 2
const startX = x.value + props.boxWidth + 1;
const startY = y.value + props.boxHeight / 2;
return `M ${startX} ${startY} L ${startX + 25} ${startY}`
})
return `M ${startX} ${startY} L ${startX + 25} ${startY}`;
});
const rootEdge = computed(() => {
if (props.node.column > 0) {
return
return;
}
const startX = 0
const startY = props.boxHeight / 2 + props.marginY / 2
const endX = x.value - 1
const endY = y.value + props.boxHeight / 2
const startX = 0;
const startY = props.boxHeight / 2 + props.marginY / 2;
const endX = x.value - 1;
const endY = y.value + props.boxHeight / 2;
return `
M ${startX} ${startY}
@@ -71,98 +82,101 @@ const rootEdge = computed(() => {
C ${endX - 25} ${startY} ${endX - 25} ${startY} ${endX - 25} ${startY + 25 * Math.sign(endY - startY)}
L ${endX - 25} ${endY - 25 * Math.sign(endY - startY)}
C ${endX - 25} ${endY} ${endX - 25} ${endY} ${endX} ${endY}
`
})
`;
});
const operator = computed(() => {
return Object.keys(props.node.rule).filter((k) => !k.startsWith('__'))[0]
})
return Object.keys(props.node.rule).filter((k) => !k.startsWith("__"))[0];
});
const variable = computed(() => {
const op = operator.value
const op = operator.value;
if (props.node.rule[op] && props.node.rule[op][0]) {
if (props.node.rule[op][0]['entries_since']) {
return 'entries_since'
if (props.node.rule[op][0]["entries_since"]) {
return "entries_since";
}
if (props.node.rule[op][0]['entries_before']) {
return 'entries_before'
if (props.node.rule[op][0]["entries_before"]) {
return "entries_before";
}
if (props.node.rule[op][0]['entries_days_since']) {
return 'entries_days_since'
if (props.node.rule[op][0]["entries_days_since"]) {
return "entries_days_since";
}
if (props.node.rule[op][0]['entries_days_before']) {
return 'entries_days_before'
if (props.node.rule[op][0]["entries_days_before"]) {
return "entries_days_before";
}
return props.node.rule[op][0]['var']
return props.node.rule[op][0]["var"];
} else {
return ''
return "";
}
})
});
const vardata = computed(() => {
return VARS[variable.value as keyof typeof VARS]
})
return VARS[variable.value as keyof typeof VARS];
});
const varresult = computed(() => {
const op = operator.value
const op = operator.value;
if (props.node.rule[op] && props.node.rule[op][0]) {
if (typeof props.node.rule[op][0]['__result'] === 'undefined')
return null
return props.node.rule[op][0]['__result']
if (typeof props.node.rule[op][0]["__result"] === "undefined") return null;
return props.node.rule[op][0]["__result"];
} else {
return ''
return "";
}
})
});
const rightoperand = computed(() => {
const op = operator.value
if (props.node.rule[op] && typeof props.node.rule[op][1] !== 'undefined') {
return props.node.rule[op][1]
const op = operator.value;
if (props.node.rule[op] && typeof props.node.rule[op][1] !== "undefined") {
return props.node.rule[op][1];
} else {
return null
return null;
}
})
});
const op = computed(() => {
return TYPEOPS[vardata.value.type as keyof typeof TYPEOPS]?.[operator.value as any]
})
return TYPEOPS[vardata.value.type as keyof typeof TYPEOPS]?.[
operator.value as any
];
});
const operands = computed(() => {
return props.node.rule[operator.value]
})
return props.node.rule[operator.value];
});
const result = computed(() => {
return typeof props.node.rule.__result === 'undefined' ? null : !!props.node.rule.__result
})
return typeof props.node.rule.__result === "undefined"
? null
: !!props.node.rule.__result;
});
const resultInclParents = computed(() => {
if (typeof props.node.rule.__result === 'undefined') return null
if (typeof props.node.rule.__result === "undefined") return null;
function _p (node: GraphNode): boolean {
function _p(node: GraphNode): boolean {
if (node.parent) {
return node.rule.__result && _p(node.parent)
return node.rule.__result && _p(node.parent);
}
return node.rule.__result
return node.rule.__result;
}
return _p(props.node)
})
return _p(props.node);
});
const nodeClass = computed(() => {
return {
node: true,
'node-true': result.value === true,
'node-false': result.value === false,
}
})
"node-true": result.value === true,
"node-false": result.value === false,
};
});
function df (val: string) {
const format = $('body').attr('data-datetimeformat')
return moment(val).format(format)
function df(val: string) {
const format = $("body").attr("data-datetimeformat");
return moment(val).format(format);
}
function tf (val: string) {
const format = $('body').attr('data-timeformat')
return moment(val, 'HH:mm:ss').format(format)
function tf(val: string) {
const format = $("body").attr("data-timeformat");
return moment(val, "HH:mm:ss").format(format);
}
</script>
<template lang="pug">
@@ -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')
@@ -0,0 +1,15 @@
document.addEventListener('DOMContentLoaded', () => {
const COOKIE_NAME = '__Host-pretix_csrftoken'
const RELOAD_FLAG = 'csrfReloadPerformed'
const hasCookie = document.cookie
.split('; ')
.some((c) => c.startsWith(COOKIE_NAME + '='))
if (!hasCookie && !sessionStorage.getItem(RELOAD_FLAG)) {
sessionStorage.setItem(RELOAD_FLAG, '1')
location.reload()
} else if (hasCookie && sessionStorage.getItem(RELOAD_FLAG)) {
sessionStorage.removeItem(RELOAD_FLAG)
}
})
@@ -1,95 +1,95 @@
import type { Category, DayEntry, EventEntry, MetaFilterField } from '~/types'
import type { Category, DayEntry, EventEntry, MetaFilterField } from "~/types";
export class ApiError extends Error {
status: number
responseUrl: string
status: number;
responseUrl: string;
constructor (status: number, responseUrl: string) {
super(`HTTP ${status}`)
this.status = status
this.responseUrl = responseUrl
constructor(status: number, responseUrl: string) {
super(`HTTP ${status}`);
this.status = status;
this.responseUrl = responseUrl;
}
}
// --- Product list ---
export interface ProductListResponse {
target_url?: string
subevent?: string | number
name?: string
frontpage_text?: string
date_range?: string
location?: string
items_by_category?: Category[]
currency?: string
currency_places?: number
display_net_prices?: boolean
voucher_explanation_text?: string
error?: string
display_add_to_cart?: boolean
waiting_list_enabled?: boolean
show_variations_expanded?: boolean
cart_exists?: boolean
vouchers_exist?: boolean
has_seating_plan?: boolean
has_seating_plan_waitinglist?: boolean
itemnum?: number
poweredby?: string
events?: EventEntry[]
has_more_events?: boolean
meta_filter_fields?: MetaFilterField[]
empty_text?: string
weeks?: DayEntry[][]
date?: string
days?: DayEntry[]
week?: [number, number]
target_url?: string;
subevent?: string | number;
name?: string;
frontpage_text?: string;
date_range?: string;
location?: string;
items_by_category?: Category[];
currency?: string;
currency_places?: number;
display_net_prices?: boolean;
voucher_explanation_text?: string;
error?: string;
display_add_to_cart?: boolean;
waiting_list_enabled?: boolean;
show_variations_expanded?: boolean;
cart_exists?: boolean;
vouchers_exist?: boolean;
has_seating_plan?: boolean;
has_seating_plan_waitinglist?: boolean;
itemnum?: number;
poweredby?: string;
events?: EventEntry[];
has_more_events?: boolean;
meta_filter_fields?: MetaFilterField[];
empty_text?: string;
weeks?: DayEntry[][];
date?: string;
days?: DayEntry[];
week?: [number, number];
}
export async function fetchProductList (url: string) {
const response = await fetch(url)
export async function fetchProductList(url: string) {
const response = await fetch(url);
if (!response.ok) {
throw new ApiError(response.status, response.url)
throw new ApiError(response.status, response.url);
}
return {
data: await response.json() as ProductListResponse,
data: (await response.json()) as ProductListResponse,
responseUrl: response.url,
}
};
}
export interface CartResponse {
redirect?: string
cart_id?: string
success?: boolean
message?: string
has_cart?: boolean
async_id?: string
check_url?: string
redirect?: string;
cart_id?: string;
success?: boolean;
message?: string;
has_cart?: boolean;
async_id?: string;
check_url?: string;
}
export async function submitCart (endpoint: string, formData: FormData) {
export async function submitCart(endpoint: string, formData: FormData) {
const response = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams(formData as any).toString(),
})
});
if (!response.ok) {
throw new ApiError(response.status, response.url)
throw new ApiError(response.status, response.url);
}
return await response.json() as CartResponse
return (await response.json()) as CartResponse;
}
export async function checkAsyncTask (url: string) {
const response = await fetch(url)
export async function checkAsyncTask(url: string) {
const response = await fetch(url);
if (!response.ok) {
throw new ApiError(response.status, response.url)
throw new ApiError(response.status, response.url);
}
return await response.json() as CartResponse
return (await response.json()) as CartResponse;
}
export async function createCart (url: string) {
const response = await fetch(url)
export async function createCart(url: string) {
const response = await fetch(url);
if (!response.ok) {
throw new ApiError(response.status, response.url)
throw new ApiError(response.status, response.url);
}
return await response.json() as CartResponse
return (await response.json()) as CartResponse;
}
@@ -1,31 +1,33 @@
import { createApp, type App } from 'vue'
import ButtonComponent from '~/components/Button.vue'
import { createWidgetStore, StoreKey } from '~/sharedStore'
import { makeid } from '~/utils'
import type { WidgetData } from '~/types'
import { createApp, type App } from "vue";
import ButtonComponent from "~/components/Button.vue";
import { createWidgetStore, StoreKey } from "~/sharedStore";
import { makeid } from "~/utils";
import type { WidgetData } from "~/types";
export function createButtonInstance (element: Element, htmlId?: string): App {
let targetUrl = element.attributes.event.value
export function createButtonInstance(element: Element, htmlId?: string): App {
let targetUrl = element.attributes.event.value;
if (!targetUrl.match(/\/$/)) {
targetUrl += '/'
targetUrl += "/";
}
const widgetData: WidgetData = JSON.parse(JSON.stringify(window.PretixWidget.widget_data))
const widgetData: WidgetData = JSON.parse(
JSON.stringify(window.PretixWidget.widget_data),
);
for (const attr of Array.from(element.attributes)) {
if (attr.name.match(/^data-.*$/)) {
widgetData[attr.name.replace(/^data-/, '')] = attr.value
widgetData[attr.name.replace(/^data-/, "")] = attr.value;
}
}
const rawItems = element.attributes.items?.value || ''
const rawItems = element.attributes.items?.value || "";
// Parse items string (format: "item_1=2,item_3=1")
const buttonItems: { item: string; count: string }[] = []
for (const itemStr of rawItems.split(',')) {
if (itemStr.includes('=')) {
const [item, count] = itemStr.split('=')
buttonItems.push({ item, count })
const buttonItems: { item: string; count: string }[] = [];
for (const itemStr of rawItems.split(",")) {
if (itemStr.includes("=")) {
const [item, count] = itemStr.split("=");
buttonItems.push({ item, count });
}
}
@@ -33,45 +35,50 @@ export function createButtonInstance (element: Element, htmlId?: string): App {
targetUrl,
voucher: element.attributes.voucher?.value || null,
subevent: element.attributes.subevent?.value || null,
skipSsl: 'skip-ssl-check' in element.attributes,
disableIframe: 'disable-iframe' in element.attributes,
skipSsl: "skip-ssl-check" in element.attributes,
disableIframe: "disable-iframe" in element.attributes,
widgetData,
htmlId: htmlId || element.id || makeid(16),
isButton: true,
buttonItems,
buttonText: element.innerHTML,
keepCart: 'keep-cart' in element.attributes || buttonItems.length > 0,
})
keepCart: "keep-cart" in element.attributes || buttonItems.length > 0,
});
const observer = new MutationObserver((mutationList) => {
for (const mutation of mutationList) {
if (mutation.type === 'attributes' && mutation.attributeName?.startsWith('data-')) {
const attrName = mutation.attributeName.substring(5)
const attrValue = (mutation.target as Element).getAttribute(mutation.attributeName)
if (
mutation.type === "attributes" &&
mutation.attributeName?.startsWith("data-")
) {
const attrName = mutation.attributeName.substring(5);
const attrValue = (mutation.target as Element).getAttribute(
mutation.attributeName,
);
if (attrValue !== null) {
store.widgetData[attrName] = attrValue
store.widgetData[attrName] = attrValue;
}
}
}
})
});
const app = createApp(ButtonComponent)
app.provide(StoreKey, store)
const app = createApp(ButtonComponent);
app.provide(StoreKey, store);
app.config.errorHandler = (error, _vm, info) => {
console.error('[pretix-button]', info, error)
}
console.error("[pretix-button]", info, error);
};
// Instead of mounting to the element directly, replicate vue2.7 behaviour, where
// the HTML-element gets replaced instead of vue3’s behaviour to replace innerHTML.
// The latter can cause issues with custom CSS as HTML structure would change.
// app.mount(element)
// observer.observe(element, { attributes: true })
const fragment = document.createDocumentFragment()
app.mount(fragment)
const fragment = document.createDocumentFragment();
app.mount(fragment);
for (const attr of element.attributes) {
fragment.firstChild.setAttribute(attr.name, attr.value)
fragment.firstChild.setAttribute(attr.name, attr.value);
}
observer.observe(fragment.firstChild, { attributes: true })
element.parentNode.replaceChild(fragment, element)
observer.observe(fragment.firstChild, { attributes: true });
element.parentNode.replaceChild(fragment, element);
return app
return app;
}
@@ -1,100 +1,120 @@
<script setup lang="ts">
import { computed, ref, inject, onMounted } from 'vue'
import type { Item, Variation } from '~/types'
import { StoreKey, globalWidgetId } from '~/sharedStore'
import { STRINGS } from '~/i18n'
import { computed, ref, inject, onMounted } from "vue";
import type { Item, Variation } from "~/types";
import { StoreKey, globalWidgetId } from "~/sharedStore";
import { STRINGS } from "~/i18n";
const props = defineProps<{
item: Item
variation?: Variation
}>()
item: Item;
variation?: Variation;
}>();
const store = inject(StoreKey)!
const quantity = ref<HTMLInputElement>()
const store = inject(StoreKey)!;
const quantity = ref<HTMLInputElement>();
const avail = computed(() => props.item.has_variations ? props.variation.avail : props.item.avail)
const avail = computed(() =>
props.item.has_variations ? props.variation.avail : props.item.avail,
);
const orderMax = computed(() => props.item.has_variations ? props.variation.order_max : props.item.order_max)
const orderMax = computed(() =>
props.item.has_variations ? props.variation.order_max : props.item.order_max,
);
const inputName = computed(() => {
if (props.item.has_variations) {
return `variation_${props.item.id}_${props.variation.id}`
return `variation_${props.item.id}_${props.variation.id}`;
}
return `item_${props.item.id}`
})
return `item_${props.item.id}`;
});
const unavailabilityReasonMessage = computed(() => {
const reason = props.item.current_unavailability_reason || props.variation?.current_unavailability_reason
const reason =
props.item.current_unavailability_reason ||
props.variation?.current_unavailability_reason;
if (reason) {
return STRINGS[`unavailable_${reason}`] || reason
return STRINGS[`unavailable_${reason}`] || reason;
}
return ''
})
return "";
});
const voucherJumpLink = computed(() => `#${store.htmlId}-voucher-input`)
const voucherJumpLink = computed(() => `#${store.htmlId}-voucher-input`);
const ariaLabelledby = computed(() => `${store.htmlId}-item-label-${props.item.id}`)
const ariaLabelledby = computed(
() => `${store.htmlId}-item-label-${props.item.id}`,
);
const decLabel = computed(() => {
// TODO
const name = props.item.has_variations ? props.variation.value : props.item.name
return `- ${name}: ${STRINGS.quantity_dec}`
})
const name = props.item.has_variations
? props.variation.value
: props.item.name;
return `- ${name}: ${STRINGS.quantity_dec}`;
});
const incLabel = computed(() => {
const name = props.item.has_variations ? props.variation.value : props.item.name
return `+ ${name}: ${STRINGS.quantity_inc}`
})
const name = props.item.has_variations
? props.variation.value
: props.item.name;
return `+ ${name}: ${STRINGS.quantity_inc}`;
});
const labelSelectItem = computed(() => {
if (props.item.has_variations) return STRINGS.select_variant.replace('%s', props.variation.value)
return STRINGS.select_item.replace('%s', props.item.name)
})
if (props.item.has_variations)
return STRINGS.select_variant.replace("%s", props.variation.value);
return STRINGS.select_item.replace("%s", props.item.name);
});
const waitingListShow = computed(() => avail.value[0] < 100 && store.waitingListEnabled && props.item.allow_waitinglist)
const waitingListShow = computed(
() =>
avail.value[0] < 100 &&
store.waitingListEnabled &&
props.item.allow_waitinglist,
);
const waitingListUrl = computed(() => {
let u = `${store.targetUrl}w/${globalWidgetId}/waitinglist/?locale=${LANG}&item=${props.item.id}`
let u = `${store.targetUrl}w/${globalWidgetId}/waitinglist/?locale=${LANG}&item=${props.item.id}`;
if (props.item.has_variations && props.variation) {
u += `&var=${props.variation.id}`
u += `&var=${props.variation.id}`;
}
if (store.subevent) {
u += `&subevent=${store.subevent}`
u += `&subevent=${store.subevent}`;
}
u += `&widget_data=${encodeURIComponent(store.widgetDataJson)}`
u += store.consentParameter
return u
})
u += `&widget_data=${encodeURIComponent(store.widgetDataJson)}`;
u += store.consentParameter;
return u;
});
function onStep (e: Event) {
const target = e.target as HTMLElement
const button = target.tagName === 'BUTTON' ? target : target.closest('button')
if (!button || !quantity.value) return
function onStep(e: Event) {
const target = e.target as HTMLElement;
const button =
target.tagName === "BUTTON" ? target : target.closest("button");
if (!button || !quantity.value) return;
const step = parseFloat(button.getAttribute('data-step') || '0')
const input = quantity.value
const min = parseFloat(input.min) || 0
const max = parseFloat(input.max) || Number.MAX_SAFE_INTEGER
const currentValue = parseInt(input.value || '0')
input.value = String(Math.max(min, Math.min(max, currentValue + step)))
input.dispatchEvent(new CustomEvent('change', { bubbles: true }))
const step = parseFloat(button.getAttribute("data-step") || "0");
const input = quantity.value;
const min = parseFloat(input.min) || 0;
const max = parseFloat(input.max) || Number.MAX_SAFE_INTEGER;
const currentValue = parseInt(input.value || "0");
input.value = String(Math.max(min, Math.min(max, currentValue + step)));
input.dispatchEvent(new CustomEvent("change", { bubbles: true }));
}
onMounted(() => {
// Auto-select first item if single item with no variations
if (
!store.cartExists
&& store.itemnum === 1
&& (!store.categories[0]?.items[0]?.has_variations || store.categories[0]?.items[0]?.variations.length < 2)
&& !store.hasSeatingPlan
&& quantity.value
!store.cartExists &&
store.itemnum === 1 &&
(!store.categories[0]?.items[0]?.has_variations ||
store.categories[0]?.items[0]?.variations.length < 2) &&
!store.hasSeatingPlan &&
quantity.value
) {
quantity.value.value = '1'
if (orderMax.value === 1 && quantity.value.type === 'checkbox') {
;(quantity.value as HTMLInputElement).checked = true
quantity.value.value = "1";
if (orderMax.value === 1 && quantity.value.type === "checkbox") {
(quantity.value as HTMLInputElement).checked = true;
}
}
})
});
</script>
<template lang="pug">
.pretix-widget-availability-box
@@ -149,5 +169,4 @@ onMounted(() => {
)
span +
</template>
<style lang="sass">
</style>
<style lang="sass"></style>
@@ -1,32 +1,32 @@
<script setup lang="ts">
import { computed, inject, ref } from 'vue'
import { StoreKey } from '~/sharedStore'
import Overlay from './Overlay.vue'
import { computed, inject, ref } from "vue";
import { StoreKey } from "~/sharedStore";
import Overlay from "./Overlay.vue";
const lang = LANG // we need this so the template sees the variable
const lang = LANG; // we need this so the template sees the variable
const store = inject(StoreKey)!
const store = inject(StoreKey)!;
const form = ref<HTMLFormElement>()
const form = ref<HTMLFormElement>();
const formMethod = computed(() => {
if (!store.useIframe && store.isButton && store.items.length === 0) {
return 'get'
return "get";
}
return 'post'
})
return "post";
});
function handleBuy (event: Event) {
function handleBuy(event: Event) {
if (form.value) {
const formData = new FormData(form.value)
store.buy(formData, event)
const formData = new FormData(form.value);
store.buy(formData, event);
}
}
defineExpose({
form,
buy: handleBuy,
})
});
</script>
<template lang="pug">
.pretix-widget-wrapper
@@ -50,5 +50,4 @@ defineExpose({
Overlay
</template>
<style lang="sass">
</style>
<style lang="sass"></style>
@@ -1,10 +1,10 @@
<script setup lang="ts">
import type { Category } from '~/types'
import Item from './Item.vue'
import type { Category } from "~/types";
import Item from "./Item.vue";
defineProps<{
category: Category
}>()
category: Category;
}>();
</script>
<template lang="pug">
@@ -19,5 +19,4 @@ defineProps<{
:category="category"
)
</template>
<style lang="sass">
</style>
<style lang="sass"></style>
@@ -1,66 +1,72 @@
<script setup lang="ts">
import { computed, inject, ref } from 'vue'
import { StoreKey } from '~/sharedStore'
import { STRINGS } from '~/i18n'
import { padNumber } from '~/utils'
import EventCalendarRow from './EventCalendarRow.vue'
import EventListFilterForm from './EventListFilterForm.vue'
import { computed, inject, ref } from "vue";
import { StoreKey } from "~/sharedStore";
import { STRINGS } from "~/i18n";
import { padNumber } from "~/utils";
import EventCalendarRow from "./EventCalendarRow.vue";
import EventListFilterForm from "./EventListFilterForm.vue";
defineProps<{
mobile: boolean
}>()
mobile: boolean;
}>();
const store = inject(StoreKey)!
const calendar = ref<HTMLDivElement>()
const store = inject(StoreKey)!;
const calendar = ref<HTMLDivElement>();
const displayEventInfo = computed(() => store.displayEventInfo || (store.displayEventInfo === null && store.parentStack.length > 0))
const displayEventInfo = computed(
() =>
store.displayEventInfo ||
(store.displayEventInfo === null && store.parentStack.length > 0),
);
const monthname = computed(() => {
// TODO proper date formatting?
if (!store.date) return ''
const monthNum = store.date.substr(5, 2)
const year = store.date.substr(0, 4)
return `${STRINGS.months[monthNum]} ${year}`
})
if (!store.date) return "";
const monthNum = store.date.substr(5, 2);
const year = store.date.substr(0, 4);
return `${STRINGS.months[monthNum]} ${year}`;
});
const id = computed(() => `${store.htmlId}-event-calendar-table`)
const id = computed(() => `${store.htmlId}-event-calendar-table`);
const ariaLabelledby = computed(() => `${store.htmlId}-event-calendar-table-label`)
const ariaLabelledby = computed(
() => `${store.htmlId}-event-calendar-table-label`,
);
function backToList () {
function backToList() {
// TODO should be in store
store.weeks = null
store.view = 'events'
store.name = null
store.frontpageText = null
store.weeks = null;
store.view = "events";
store.name = null;
store.frontpageText = null;
}
function prevmonth () {
if (!store.date) return
let curMonth = parseInt(store.date.substr(5, 2))
let curYear = parseInt(store.date.substr(0, 4))
curMonth--
function prevmonth() {
if (!store.date) return;
let curMonth = parseInt(store.date.substr(5, 2));
let curYear = parseInt(store.date.substr(0, 4));
curMonth--;
if (curMonth < 1) {
curMonth = 12
curYear--
curMonth = 12;
curYear--;
}
store.date = `${curYear}-${padNumber(curMonth, 2)}-01`
store.loading++
store.reload({ focus: `#${id.value}` })
store.date = `${curYear}-${padNumber(curMonth, 2)}-01`;
store.loading++;
store.reload({ focus: `#${id.value}` });
}
function nextmonth () {
if (!store.date) return
let curMonth = parseInt(store.date.substr(5, 2))
let curYear = parseInt(store.date.substr(0, 4))
curMonth++
function nextmonth() {
if (!store.date) return;
let curMonth = parseInt(store.date.substr(5, 2));
let curYear = parseInt(store.date.substr(0, 4));
curMonth++;
if (curMonth > 12) {
curMonth = 1
curYear++
curMonth = 1;
curYear++;
}
store.date = `${curYear}-${padNumber(curMonth, 2)}-01`
store.loading++
store.reload({ focus: `#${id.value}` })
store.date = `${curYear}-${padNumber(curMonth, 2)}-01`;
store.loading++;
store.reload({ focus: `#${id.value}` });
}
</script>
<template lang="pug">
@@ -116,5 +122,4 @@ function nextmonth () {
:mobile="mobile"
)
</template>
<style lang="sass">
</style>
<style lang="sass"></style>
@@ -1,108 +1,117 @@
<script setup lang="ts">
import { computed, inject, ref, onMounted, watch } from 'vue'
import type { DayEntry } from '~/types'
import { StoreKey } from '~/sharedStore'
import EventCalendarEvent from './EventCalendarEvent.vue'
import { computed, inject, ref, onMounted, watch } from "vue";
import type { DayEntry } from "~/types";
import { StoreKey } from "~/sharedStore";
import EventCalendarEvent from "./EventCalendarEvent.vue";
const props = defineProps<{
day: DayEntry | null
mobile: boolean
}>()
day: DayEntry | null;
mobile: boolean;
}>();
const store = inject(StoreKey)!
const cellEl = ref<HTMLTableCellElement>()
const store = inject(StoreKey)!;
const cellEl = ref<HTMLTableCellElement>();
const daynum = computed(() => {
if (!props.day) return ''
return props.day.date.substr(8)
})
if (!props.day) return "";
return props.day.date.substr(8);
});
const dateStr = computed(() => props.day ? new Date(props.day.date).toLocaleDateString() : '')
const dateStr = computed(() =>
props.day ? new Date(props.day.date).toLocaleDateString() : "",
);
const role = computed(() => !props.day || !props.day.events.length || !props.mobile ? 'cell' : 'button')
const role = computed(() =>
!props.day || !props.day.events.length || !props.mobile ? "cell" : "button",
);
const tabindex = computed(() => role.value === 'button' ? '0' : '-1')
const tabindex = computed(() => (role.value === "button" ? "0" : "-1"));
const classObject = computed(() => {
const o: Record<string, boolean> = {}
const o: Record<string, boolean> = {};
if (props.day && props.day.events.length > 0) {
o['pretix-widget-has-events'] = true // TODO static
let best = 'red'
let allLow = true
o["pretix-widget-has-events"] = true; // TODO static
let best = "red";
let allLow = true;
// TODO decopypasta
for (const ev of props.day.events) {
if (ev.availability.color === 'green') {
best = 'green'
if (ev.availability.reason !== 'low') {
allLow = false
if (ev.availability.color === "green") {
best = "green";
if (ev.availability.reason !== "low") {
allLow = false;
}
} else if (ev.availability.color === 'orange' && best !== 'green') {
best = 'orange'
} else if (ev.availability.color === "orange" && best !== "green") {
best = "orange";
}
}
o[`pretix-widget-day-availability-${best}`] = true
if (best === 'green' && allLow) {
o['pretix-widget-day-availability-low'] = true
o[`pretix-widget-day-availability-${best}`] = true;
if (best === "green" && allLow) {
o["pretix-widget-day-availability-low"] = true;
}
}
return o
})
return o;
});
function selectDay (e: Event) {
if (!props.day || !props.day.events.length || !props.mobile) return
e.preventDefault()
e.stopPropagation()
function selectDay(e: Event) {
if (!props.day || !props.day.events.length || !props.mobile) return;
e.preventDefault();
e.stopPropagation();
// TODO decopypasta
if (props.day.events.length === 1) {
const ev = props.day.events[0]
store.parentStack.push(store.targetUrl)
store.targetUrl = ev.event_url
store.error = null
store.subevent = ev.subevent ?? null
store.loading++
store.reload()
const ev = props.day.events[0];
store.parentStack.push(store.targetUrl);
store.targetUrl = ev.event_url;
store.error = null;
store.subevent = ev.subevent ?? null;
store.loading++;
store.reload();
} else {
store.events = props.day.events
store.view = 'events'
store.events = props.day.events;
store.view = "events";
}
}
function onKeyDown (e: KeyboardEvent) {
const keyDown = e.key ?? e.keyCode
if (keyDown === 'Enter' || keyDown === 13 || ['Spacebar', ' '].includes(keyDown as string) || keyDown === 32) {
function onKeyDown(e: KeyboardEvent) {
const keyDown = e.key ?? e.keyCode;
if (
keyDown === "Enter" ||
keyDown === 13 ||
["Spacebar", " "].includes(keyDown as string) ||
keyDown === 32
) {
// (prevent default so the page doesn't scroll when pressing space)
e.preventDefault()
selectDay(e)
e.preventDefault();
selectDay(e);
}
}
function attachListeners () {
if (role.value === 'button' && cellEl.value) {
cellEl.value.addEventListener('click', selectDay)
cellEl.value.addEventListener('keydown', onKeyDown)
function attachListeners() {
if (role.value === "button" && cellEl.value) {
cellEl.value.addEventListener("click", selectDay);
cellEl.value.addEventListener("keydown", onKeyDown);
}
}
function detachListeners () {
function detachListeners() {
if (cellEl.value) {
cellEl.value.removeEventListener('click', selectDay)
cellEl.value.removeEventListener('keydown', onKeyDown)
cellEl.value.removeEventListener("click", selectDay);
cellEl.value.removeEventListener("keydown", onKeyDown);
}
}
onMounted(() => {
attachListeners()
})
attachListeners();
});
// TODO why different from old version?
watch(role, (newValue, oldValue) => {
if (newValue === 'button' && oldValue !== 'button') {
attachListeners()
} else if (newValue !== 'button' && oldValue === 'button') {
detachListeners()
if (newValue === "button" && oldValue !== "button") {
attachListeners();
} else if (newValue !== "button" && oldValue === "button") {
detachListeners();
}
})
});
</script>
<template lang="pug">
td(
@@ -116,5 +125,4 @@ td(
.pretix-widget-event-calendar-events(v-if="day")
EventCalendarEvent(v-for="e in day.events", :key="e.event_url+'-'+(e.subevent||'')", :event="e")
</template>
<style lang="sass">
</style>
<style lang="sass"></style>
@@ -1,33 +1,35 @@
<script setup lang="ts">
import { computed, inject } from 'vue'
import type { EventEntry } from '~/types'
import { StoreKey } from '~/sharedStore'
import { computed, inject } from "vue";
import type { EventEntry } from "~/types";
import { StoreKey } from "~/sharedStore";
const props = defineProps<{
event: EventEntry
describedby?: string
}>()
event: EventEntry;
describedby?: string;
}>();
const store = inject(StoreKey)!
const store = inject(StoreKey)!;
const classObject = computed(() => {
const o: Record<string, boolean> = {
'pretix-widget-event-calendar-event': true,
}
o[`pretix-widget-event-availability-${props.event.availability.color}`] = true
"pretix-widget-event-calendar-event": true,
};
o[`pretix-widget-event-availability-${props.event.availability.color}`] =
true;
if (props.event.availability.reason) {
o[`pretix-widget-event-availability-${props.event.availability.reason}`] = true
o[`pretix-widget-event-availability-${props.event.availability.reason}`] =
true;
}
return o
})
return o;
});
function select () {
store.parentStack.push(store.targetUrl)
store.targetUrl = props.event.event_url
store.error = null
store.subevent = props.event.subevent ?? null
store.loading++
store.reload()
function select() {
store.parentStack.push(store.targetUrl);
store.targetUrl = props.event.event_url;
store.error = null;
store.subevent = props.event.subevent ?? null;
store.loading++;
store.reload();
}
</script>
<template lang="pug">
@@ -41,5 +43,4 @@ a.pretix-widget-event-calendar-event(
.pretix-widget-event-calendar-event-date(v-if="!event.continued && event.time") {{ event.time }}
.pretix-widget-event-calendar-event-availability(v-if="!event.continued && event.availability.text") {{ event.availability.text }}
</template>
<style lang="sass">
</style>
<style lang="sass"></style>
@@ -1,15 +1,14 @@
<script setup lang="ts">
import type { DayEntry } from '~/types'
import EventCalendarCell from './EventCalendarCell.vue'
import type { DayEntry } from "~/types";
import EventCalendarCell from "./EventCalendarCell.vue";
defineProps<{
week: (DayEntry | null)[]
mobile: boolean
}>()
week: (DayEntry | null)[];
mobile: boolean;
}>();
</script>
<template lang="pug">
tr
EventCalendarCell(v-for="(d, idx) in week", :key="idx", :day="d", :mobile="mobile")
</template>
<style lang="sass">
</style>
<style lang="sass"></style>
@@ -1,119 +1,148 @@
<script setup lang="ts">
import { computed, inject, ref, watch, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { StoreKey } from '~/sharedStore'
import { STRINGS } from '~/i18n'
import Category from './Category.vue'
import {
computed,
inject,
ref,
watch,
onMounted,
onBeforeUnmount,
nextTick,
} from "vue";
import { StoreKey } from "~/sharedStore";
import { STRINGS } from "~/i18n";
import Category from "./Category.vue";
const store = inject(StoreKey)!
const store = inject(StoreKey)!;
const form = ref<HTMLFormElement>()
const voucherinput = ref<HTMLInputElement>()
const isItemsSelected = ref(false)
const localVoucher = ref('')
const form = ref<HTMLFormElement>();
const voucherinput = ref<HTMLInputElement>();
const isItemsSelected = ref(false);
const localVoucher = ref("");
const idVoucherInput = computed(() => `${store.htmlId}-voucher-input`)
const ariaLabelledby = computed(() => `${store.htmlId}-voucher-headline`)
const displayEventInfo = computed(() => store.displayEventInfo || (store.displayEventInfo === null && (store.events || store.weeks || store.days)))
const idCartExistsMsg = computed(() => `${store.htmlId}-cart-exists`)
const idVoucherInput = computed(() => `${store.htmlId}-voucher-input`);
const ariaLabelledby = computed(() => `${store.htmlId}-voucher-headline`);
const displayEventInfo = computed(
() =>
store.displayEventInfo ||
(store.displayEventInfo === null &&
(store.events || store.weeks || store.days)),
);
const idCartExistsMsg = computed(() => `${store.htmlId}-cart-exists`);
const buyLabel = computed(() => {
let allFree = true
let allFree = true;
for (const cat of store.categories) {
for (const item of cat.items) {
for (const v of item.variations) {
if (v.price.gross !== '0.00') {
allFree = false
break
if (v.price.gross !== "0.00") {
allFree = false;
break;
}
}
if ((item.variations.length === 0 && item.price.gross !== '0.00') || item.mandatory_priced_addons) {
allFree = false
break
if (
(item.variations.length === 0 && item.price.gross !== "0.00") ||
item.mandatory_priced_addons
) {
allFree = false;
break;
}
}
if (!allFree) break
if (!allFree) break;
}
return allFree ? STRINGS.register : STRINGS.buy
})
return allFree ? STRINGS.register : STRINGS.buy;
});
const hiddenParams = computed(() => {
const params = new URL(store.getVoucherFormTarget()).searchParams
params.delete('iframe')
params.delete('take_cart_id')
return [...params.entries()]
})
const params = new URL(store.getVoucherFormTarget()).searchParams;
params.delete("iframe");
params.delete("take_cart_id");
return [...params.entries()];
});
const showVoucherForm = computed(() => store.vouchersExist && !store.disableVouchers && !store.voucherCode)
const showVoucherForm = computed(
() => store.vouchersExist && !store.disableVouchers && !store.voucherCode,
);
async function backToList () {
store.targetUrl = store.parentStack.pop() || store.targetUrl
store.error = null
async function backToList() {
store.targetUrl = store.parentStack.pop() || store.targetUrl;
store.error = null;
if (!store.subevent) {
// reset if we are not in a series
store.name = null
store.frontpageText = null
store.name = null;
store.frontpageText = null;
}
store.subevent = null
store.offset = 0
store.appendEvents = false
store.triggerLoadCallback()
store.subevent = null;
store.offset = 0;
store.appendEvents = false;
store.triggerLoadCallback();
if (store.events !== undefined && store.events !== null) {
store.view = 'events'
store.view = "events";
} else if (store.days !== undefined && store.days !== null) {
store.view = 'days'
store.view = "days";
} else {
store.view = 'weeks'
store.view = "weeks";
}
// wait for redraw, then focus content element for better a11y
const rootEl = form.value?.closest('.pretix-widget-wrapper') as HTMLElement | null
await nextTick()
rootEl?.focus()
const rootEl = form.value?.closest(
".pretix-widget-wrapper",
) as HTMLElement | null;
await nextTick();
rootEl?.focus();
}
function calcItemsSelected () {
if (!form.value) return
const checkboxes = form.value.querySelectorAll<HTMLInputElement>('input[type=checkbox], input[type=radio]')
const hasChecked = Array.from(checkboxes).some((el) => el.checked)
const numberInputs = form.value.querySelectorAll<HTMLInputElement>('.pretix-widget-item-count-group input')
const hasQuantity = Array.from(numberInputs).some((el) => parseInt(el.value || '0') > 0)
isItemsSelected.value = hasChecked || hasQuantity
function calcItemsSelected() {
if (!form.value) return;
const checkboxes = form.value.querySelectorAll<HTMLInputElement>(
"input[type=checkbox], input[type=radio]",
);
const hasChecked = Array.from(checkboxes).some((el) => el.checked);
const numberInputs = form.value.querySelectorAll<HTMLInputElement>(
".pretix-widget-item-count-group input",
);
const hasQuantity = Array.from(numberInputs).some(
(el) => parseInt(el.value || "0") > 0,
);
isItemsSelected.value = hasChecked || hasQuantity;
}
function _focusVoucherField () {
voucherinput.value?.focus()
function _focusVoucherField() {
voucherinput.value?.focus();
}
function handleBuy (event: Event) {
function handleBuy(event: Event) {
if (form.value) {
const formData = new FormData(form.value)
store.buy(formData, event)
const formData = new FormData(form.value);
store.buy(formData, event);
}
}
function handleRedeem (event: Event) {
store.redeem(localVoucher.value, event)
function handleRedeem(event: Event) {
store.redeem(localVoucher.value, event);
}
onMounted(() => {
if (form.value) {
form.value.addEventListener('change', calcItemsSelected)
form.value.addEventListener("change", calcItemsSelected);
}
})
});
onBeforeUnmount(() => {
if (form.value) {
form.value.removeEventListener('change', calcItemsSelected)
form.value.removeEventListener("change", calcItemsSelected);
}
})
});
watch(() => store.overlay?.frameShown, (newValue) => {
if (!newValue && form.value) {
form.value.reset()
calcItemsSelected()
}
})
watch(
() => store.overlay?.frameShown,
(newValue) => {
if (!newValue && form.value) {
form.value.reset();
calcItemsSelected();
}
},
);
</script>
<template lang="pug">
@@ -233,5 +262,4 @@ watch(() => store.overlay?.frameShown, (newValue) => {
button(@click="handleRedeem") {{ STRINGS.redeem }}
.pretix-widget-clear
</template>
<style lang="sass">
</style>
<style lang="sass"></style>
@@ -1,44 +1,50 @@
<script setup lang="ts">
import { computed, inject, nextTick } from 'vue'
import { StoreKey } from '~/sharedStore'
import { STRINGS } from '~/i18n'
import EventListEntry from './EventListEntry.vue'
import EventListFilterForm from './EventListFilterForm.vue'
import { computed, inject, nextTick } from "vue";
import { StoreKey } from "~/sharedStore";
import { STRINGS } from "~/i18n";
import EventListEntry from "./EventListEntry.vue";
import EventListFilterForm from "./EventListFilterForm.vue";
const store = inject(StoreKey)!
const store = inject(StoreKey)!;
const displayEventInfo = computed(() => store.displayEventInfo || (store.displayEventInfo === null && store.parentStack.length > 0))
const displayEventInfo = computed(
() =>
store.displayEventInfo ||
(store.displayEventInfo === null && store.parentStack.length > 0),
);
async function backToCalendar (event: MouseEvent) {
async function backToCalendar(event: MouseEvent) {
// make sure to always focus content element
await nextTick()
const rootEl = (event.target as HTMLElement).closest('.pretix-widget-wrapper') as HTMLElement | null
rootEl?.focus()
await nextTick();
const rootEl = (event.target as HTMLElement).closest(
".pretix-widget-wrapper",
) as HTMLElement | null;
rootEl?.focus();
store.offset = 0
store.appendEvents = false
store.offset = 0;
store.appendEvents = false;
if (store.weeks) {
store.events = null
store.view = 'weeks'
store.name = null
store.frontpageText = null
store.events = null;
store.view = "weeks";
store.name = null;
store.frontpageText = null;
} else {
store.loading++
store.targetUrl = store.parentStack.pop() || store.targetUrl
store.error = null
store.reload()
store.loading++;
store.targetUrl = store.parentStack.pop() || store.targetUrl;
store.error = null;
store.reload();
}
}
function loadMore () {
store.appendEvents = true
store.offset += 50
store.loading++
store.reload()
function loadMore() {
store.appendEvents = true;
store.offset += 50;
store.loading++;
store.reload();
}
console.log(store)
console.log(store);
</script>
<template lang="pug">
.pretix-widget-event-list
@@ -67,5 +73,4 @@ console.log(store)
p.pretix-widget-event-list-load-more(v-if="store.hasMoreEvents")
button(@click.prevent.stop="loadMore") {{ STRINGS.load_more }}
</template>
<style lang="sass">
</style>
<style lang="sass"></style>
@@ -1,34 +1,38 @@
<script setup lang="ts">
import { computed, inject } from 'vue'
import type { EventEntry } from '~/types'
import { StoreKey } from '~/sharedStore'
import { computed, inject } from "vue";
import type { EventEntry } from "~/types";
import { StoreKey } from "~/sharedStore";
const props = defineProps<{
event: EventEntry
}>()
event: EventEntry;
}>();
const store = inject(StoreKey)!
const store = inject(StoreKey)!;
const classObject = computed(() => {
const o: Record<string, boolean> = {
'pretix-widget-event-list-entry': true,
}
o[`pretix-widget-event-availability-${props.event.availability.color}`] = true
"pretix-widget-event-list-entry": true,
};
o[`pretix-widget-event-availability-${props.event.availability.color}`] =
true;
if (props.event.availability.reason) {
o[`pretix-widget-event-availability-${props.event.availability.reason}`] = true
o[`pretix-widget-event-availability-${props.event.availability.reason}`] =
true;
}
return o
})
return o;
});
const location = computed(() => props.event.location.replace(/\s*\n\s*/g, ', '))
const location = computed(() =>
props.event.location.replace(/\s*\n\s*/g, ", "),
);
function select () {
store.parentStack.push(store.targetUrl)
store.targetUrl = props.event.event_url
store.error = null
store.subevent = props.event.subevent ?? null
store.loading++
store.reload()
function select() {
store.parentStack.push(store.targetUrl);
store.targetUrl = props.event.event_url;
store.error = null;
store.subevent = props.event.subevent ?? null;
store.loading++;
store.reload();
}
</script>
<template lang="pug">
@@ -40,5 +44,4 @@ a.pretix-widget-event-list-entry(href="#", :class="classObject", @click.prevent.
.pretix-widget-event-list-entry-availability
span {{ event.availability.text }}
</template>
<style lang="sass">
</style>
<style lang="sass"></style>
@@ -1,20 +1,20 @@
<script setup lang="ts">
import { computed, inject } from 'vue'
import type { MetaFilterField } from '~/types'
import { StoreKey, globalWidgetId } from '~/sharedStore'
import { computed, inject } from "vue";
import type { MetaFilterField } from "~/types";
import { StoreKey, globalWidgetId } from "~/sharedStore";
const props = defineProps<{
field: MetaFilterField
}>()
field: MetaFilterField;
}>();
const store = inject(StoreKey)!
const store = inject(StoreKey)!;
const id = computed(() => `${globalWidgetId}_${props.field.key}`)
const id = computed(() => `${globalWidgetId}_${props.field.key}`);
const currentValue = computed(() => {
const filterParams = new URLSearchParams(store.filter || '')
return filterParams.get(props.field.key) || ''
})
const filterParams = new URLSearchParams(store.filter || "");
return filterParams.get(props.field.key) || "";
});
</script>
<template lang="pug">
.pretix-widget-event-list-filter-field
@@ -22,5 +22,4 @@ const currentValue = computed(() => {
select(:id="id", :name="field.key", :value="currentValue")
option(v-for="choice in field.choices", :key="choice[0]", :value="choice[0]") {{ choice[1] }}
</template>
<style lang="sass">
</style>
<style lang="sass"></style>
@@ -1,28 +1,28 @@
<script setup lang="ts">
import { inject, ref } from 'vue'
import { StoreKey } from '~/sharedStore'
import { STRINGS } from '~/i18n'
import EventListFilterField from './EventListFilterField.vue'
import { inject, ref } from "vue";
import { StoreKey } from "~/sharedStore";
import { STRINGS } from "~/i18n";
import EventListFilterField from "./EventListFilterField.vue";
const store = inject(StoreKey)!
const filterform = ref<HTMLFormElement>()
const store = inject(StoreKey)!;
const filterform = ref<HTMLFormElement>();
function onSubmit (e: Event) {
e.preventDefault()
if (!filterform.value) return
function onSubmit(e: Event) {
e.preventDefault();
if (!filterform.value) return;
const formData = new FormData(filterform.value)
const filterParams = new URLSearchParams()
const formData = new FormData(filterform.value);
const filterParams = new URLSearchParams();
formData.forEach((value, key) => {
if (value !== '') {
filterParams.set(key, value as string)
if (value !== "") {
filterParams.set(key, value as string);
}
})
});
store.filter = filterParams.toString()
store.loading++
store.reload()
store.filter = filterParams.toString();
store.loading++;
store.reload();
}
</script>
<template lang="pug">
@@ -36,5 +36,4 @@ form.pretix-widget-event-list-filter-form(ref="filterform", @submit="onSubmit")
)
button {{ STRINGS.filter }}
</template>
<style lang="sass">
</style>
<style lang="sass"></style>
@@ -1,62 +1,66 @@
<script setup lang="ts">
import { computed, inject, ref } from 'vue'
import { StoreKey } from '~/sharedStore'
import { STRINGS } from '~/i18n'
import { getISOWeeks } from '~/utils'
import EventWeekCell from './EventWeekCell.vue'
import EventListFilterForm from './EventListFilterForm.vue'
import { computed, inject, ref } from "vue";
import { StoreKey } from "~/sharedStore";
import { STRINGS } from "~/i18n";
import { getISOWeeks } from "~/utils";
import EventWeekCell from "./EventWeekCell.vue";
import EventListFilterForm from "./EventListFilterForm.vue";
defineProps<{
mobile: boolean
}>()
mobile: boolean;
}>();
const store = inject(StoreKey)!
const weekcalendar = ref<HTMLDivElement>()
const store = inject(StoreKey)!;
const weekcalendar = ref<HTMLDivElement>();
const displayEventInfo = computed(() => store.displayEventInfo || (store.displayEventInfo === null && store.parentStack.length > 0))
const displayEventInfo = computed(
() =>
store.displayEventInfo ||
(store.displayEventInfo === null && store.parentStack.length > 0),
);
const weekname = computed(() => {
if (!store.week) return ''
const curWeek = store.week[1]
const curYear = store.week[0]
return `${curWeek} / ${curYear}`
})
if (!store.week) return "";
const curWeek = store.week[1];
const curYear = store.week[0];
return `${curWeek} / ${curYear}`;
});
const id = computed(() => `${store.htmlId}-event-week-table`)
const id = computed(() => `${store.htmlId}-event-week-table`);
function backToList () {
store.weeks = null
store.name = null
store.frontpageText = null
store.view = 'events'
function backToList() {
store.weeks = null;
store.name = null;
store.frontpageText = null;
store.view = "events";
}
function prevweek () {
if (!store.week) return
let curWeek = store.week[1]
let curYear = store.week[0]
curWeek--
function prevweek() {
if (!store.week) return;
let curWeek = store.week[1];
let curYear = store.week[0];
curWeek--;
if (curWeek < 1) {
curYear--
curWeek = getISOWeeks(curYear)
curYear--;
curWeek = getISOWeeks(curYear);
}
store.week = [curYear, curWeek]
store.loading++
store.reload({ focus: `#${id.value}` })
store.week = [curYear, curWeek];
store.loading++;
store.reload({ focus: `#${id.value}` });
}
function nextweek () {
if (!store.week) return
let curWeek = store.week[1]
let curYear = store.week[0]
curWeek++
function nextweek() {
if (!store.week) return;
let curWeek = store.week[1];
let curYear = store.week[0];
curWeek++;
if (curWeek > getISOWeeks(curYear)) {
curWeek = 1
curYear++
curWeek = 1;
curYear++;
}
store.week = [curYear, curWeek]
store.loading++
store.reload({ focus: `#${id.value}` })
store.week = [curYear, curWeek];
store.loading++;
store.reload({ focus: `#${id.value}` });
}
</script>
<template lang="pug">
@@ -93,5 +97,4 @@ function nextweek () {
.pretix-widget-event-week-col(v-for="d in store.days", :key="d?.date || ''")
EventWeekCell(:day="d", :mobile="mobile")
</template>
<style lang="sass">
</style>
<style lang="sass"></style>
@@ -1,62 +1,64 @@
<script setup lang="ts">
import { computed, inject } from 'vue'
import type { DayEntry } from '~/types'
import { StoreKey } from '~/sharedStore'
import EventCalendarEvent from './EventCalendarEvent.vue'
import { computed, inject } from "vue";
import type { DayEntry } from "~/types";
import { StoreKey } from "~/sharedStore";
import EventCalendarEvent from "./EventCalendarEvent.vue";
const props = defineProps<{
day: DayEntry | null
mobile: boolean // TODO inject?
}>()
day: DayEntry | null;
mobile: boolean; // TODO inject?
}>();
const store = inject(StoreKey)!
const store = inject(StoreKey)!;
const id = computed(() => props.day ? `${store.htmlId}-${props.day.date}` : '')
const id = computed(() =>
props.day ? `${store.htmlId}-${props.day.date}` : "",
);
const dayhead = computed(() => {
if (!props.day) return ''
return props.day.day_formatted
})
if (!props.day) return "";
return props.day.day_formatted;
});
const classObject = computed(() => {
const o: Record<string, boolean> = {}
const o: Record<string, boolean> = {};
if (props.day && props.day.events.length > 0) {
o['pretix-widget-has-events'] = true
let best = 'red'
let allLow = true
o["pretix-widget-has-events"] = true;
let best = "red";
let allLow = true;
for (const ev of props.day.events) {
if (ev.availability.color === 'green') {
best = 'green'
if (ev.availability.reason !== 'low') {
allLow = false
if (ev.availability.color === "green") {
best = "green";
if (ev.availability.reason !== "low") {
allLow = false;
}
} else if (ev.availability.color === 'orange' && best !== 'green') {
best = 'orange'
} else if (ev.availability.color === "orange" && best !== "green") {
best = "orange";
}
}
o[`pretix-widget-day-availability-${best}`] = true
if (best === 'green' && allLow) {
o['pretix-widget-day-availability-low'] = true
o[`pretix-widget-day-availability-${best}`] = true;
if (best === "green" && allLow) {
o["pretix-widget-day-availability-low"] = true;
}
}
return o
})
return o;
});
function selectDay () {
if (!props.day || !props.day.events.length || !props.mobile) return
function selectDay() {
if (!props.day || !props.day.events.length || !props.mobile) return;
if (props.day.events.length === 1) {
const ev = props.day.events[0]
const ev = props.day.events[0];
// TODO store mutation bad
store.parentStack.push(store.targetUrl)
store.targetUrl = ev.event_url
store.error = null
store.subevent = ev.subevent ?? null
store.loading++
store.reload()
store.parentStack.push(store.targetUrl);
store.targetUrl = ev.event_url;
store.error = null;
store.subevent = ev.subevent ?? null;
store.loading++;
store.reload();
} else {
store.events = props.day.events
store.view = 'events'
store.events = props.day.events;
store.view = "events";
}
}
</script>
@@ -71,5 +73,4 @@ div(:class="classObject", @click.prevent.stop="selectDay")
:describedby="id"
)
</template>
<style lang="sass">
</style>
<style lang="sass"></style>
@@ -1,69 +1,83 @@
<script setup lang="ts">
import { computed, inject, ref, watch, onMounted } from 'vue'
import type { Item, Category } from '~/types'
import { StoreKey } from '~/sharedStore'
import { STRINGS, interpolate } from '~/i18n'
import { floatformat } from '~/utils'
import AvailBox from './AvailBox.vue'
import PriceBox from './PriceBox.vue'
import Variation from './Variation.vue'
import { computed, inject, ref, watch, onMounted } from "vue";
import type { Item, Category } from "~/types";
import { StoreKey } from "~/sharedStore";
import { STRINGS, interpolate } from "~/i18n";
import { floatformat } from "~/utils";
import AvailBox from "./AvailBox.vue";
import PriceBox from "./PriceBox.vue";
import Variation from "./Variation.vue";
const props = defineProps<{
item: Item
category: Category
}>()
item: Item;
category: Category;
}>();
const store = inject(StoreKey)!
const store = inject(StoreKey)!;
const expanded = ref(store.showVariationsExpanded)
const variations = ref<HTMLDivElement>()
const expanded = ref(store.showVariationsExpanded);
const variations = ref<HTMLDivElement>();
const classObject = computed(() => ({
'pretix-widget-item': true,
'pretix-widget-item-with-picture': !!props.item.picture,
'pretix-widget-item-with-variations': props.item.has_variations,
}))
"pretix-widget-item": true,
"pretix-widget-item-with-picture": !!props.item.picture,
"pretix-widget-item-with-variations": props.item.has_variations,
}));
const varClasses = computed(() => ({
'pretix-widget-item-variations': true,
'pretix-widget-item-variations-expanded': expanded.value,
}))
"pretix-widget-item-variations": true,
"pretix-widget-item-variations-expanded": expanded.value,
}));
const pictureAltText = computed(() => interpolate(STRINGS.image_of, [props.item.name]))
const pictureAltText = computed(() =>
interpolate(STRINGS.image_of, [props.item.name]),
);
const headingLevel = computed(() => props.category.name ? '4' : '3')
const headingLevel = computed(() => (props.category.name ? "4" : "3"));
const itemLabelId = computed(() => `${store.htmlId}-item-label-${props.item.id}`)
const itemLabelId = computed(
() => `${store.htmlId}-item-label-${props.item.id}`,
);
const itemDescId = computed(() => `${store.htmlId}-item-desc-${props.item.id}`)
const itemDescId = computed(() => `${store.htmlId}-item-desc-${props.item.id}`);
const itemPriceId = computed(() => `${store.htmlId}-item-price-${props.item.id}`)
const itemPriceId = computed(
() => `${store.htmlId}-item-price-${props.item.id}`,
);
const ariaLabelledby = computed(() => `${itemLabelId.value} ${itemPriceId.value}`)
const ariaLabelledby = computed(
() => `${itemLabelId.value} ${itemPriceId.value}`,
);
const minOrderStr = computed(() => interpolate(STRINGS.order_min, [props.item.order_min]))
const minOrderStr = computed(() =>
interpolate(STRINGS.order_min, [props.item.order_min]),
);
const quotaLeftStr = computed(() => interpolate(STRINGS.quota_left, [props.item.avail[1]]))
const quotaLeftStr = computed(() =>
interpolate(STRINGS.quota_left, [props.item.avail[1]]),
);
const showToggle = computed(() => props.item.has_variations && !store.showVariationsExpanded)
const showToggle = computed(
() => props.item.has_variations && !store.showVariationsExpanded,
);
// TODO dedupe?
const showPrices = computed(() => {
let hasPriced = false
let cntItems = 0
let hasPriced = false;
let cntItems = 0;
for (const cat of store.categories) {
for (const item of cat.items) {
if (item.has_variations) {
cntItems += item.variations.length
hasPriced = true
cntItems += item.variations.length;
hasPriced = true;
} else {
cntItems++
hasPriced = hasPriced || item.price.gross !== '0.00' || item.free_price
cntItems++;
hasPriced = hasPriced || item.price.gross !== "0.00" || item.free_price;
}
}
}
return hasPriced || cntItems > 1
})
return hasPriced || cntItems > 1;
});
// TODO XSS
const pricerange = computed(() => {
@@ -72,68 +86,73 @@ const pricerange = computed(() => {
STRINGS.price_from,
{
currency: store.currency,
price: floatformat(props.item.min_price || '0', store.currency_places),
price: floatformat(props.item.min_price || "0", store.currency_places),
},
true
true,
).replace(
store.currency,
`<span class="pretix-widget-pricebox-currency">${store.currency}</span>`
)
`<span class="pretix-widget-pricebox-currency">${store.currency}</span>`,
);
} else if (props.item.min_price !== props.item.max_price) {
return `<span class="pretix-widget-pricebox-currency">${store.currency}</span> ${floatformat(props.item.min_price || '0', store.currency_places)} – ${floatformat(props.item.max_price || '0', store.currency_places)}`
} else if (props.item.min_price === '0.00' && props.item.max_price === '0.00') {
return `<span class="pretix-widget-pricebox-currency">${store.currency}</span> ${floatformat(props.item.min_price || "0", store.currency_places)} – ${floatformat(props.item.max_price || "0", store.currency_places)}`;
} else if (
props.item.min_price === "0.00" &&
props.item.max_price === "0.00"
) {
if (props.item.mandatory_priced_addons) {
return '\xA0' // nbsp, because an empty string would cause the HTML element to collapse
return "\xA0"; // nbsp, because an empty string would cause the HTML element to collapse
}
return STRINGS.free
return STRINGS.free;
} else {
return `<span class="pretix-widget-pricebox-currency">${store.currency}</span> ${floatformat(props.item.min_price || '0', store.currency_places)}`
return `<span class="pretix-widget-pricebox-currency">${store.currency}</span> ${floatformat(props.item.min_price || "0", store.currency_places)}`;
}
})
});
const variationsToggleLabel = computed(() => expanded.value ? STRINGS.hide_variations : STRINGS.variations)
const variationsToggleLabel = computed(() =>
expanded.value ? STRINGS.hide_variations : STRINGS.variations,
);
function expand () {
expanded.value = !expanded.value
function expand() {
expanded.value = !expanded.value;
}
function lightbox () {
function lightbox() {
if (store.overlay) {
store.overlay.lightbox = {
image: props.item.picture_fullsize || '',
image: props.item.picture_fullsize || "",
description: props.item.name,
loading: true, // TODO why?
}
};
}
}
onMounted(() => {
if (variations.value && !expanded.value) {
variations.value.hidden = true
variations.value.hidden = true;
variations.value.addEventListener('transitionend', function (event) {
variations.value.addEventListener("transitionend", function (event) {
if (event.target === variations.value) {
if (variations.value) {
variations.value.hidden = !expanded.value
variations.value.style.maxHeight = 'none'
variations.value.hidden = !expanded.value;
variations.value.style.maxHeight = "none";
}
}
})
});
}
})
});
watch(expanded, (newValue) => {
const v = variations.value
if (!v) return
const v = variations.value;
if (!v) return;
v.hidden = false
v.style.maxHeight = `${newValue ? 0 : v.scrollHeight}px`
v.hidden = false;
v.style.maxHeight = `${newValue ? 0 : v.scrollHeight}px`;
// Vue.nextTick does not work here
setTimeout(() => {
v.style.maxHeight = `${!newValue ? 0 : v.scrollHeight}px`
}, 50)
})
v.style.maxHeight = `${!newValue ? 0 : v.scrollHeight}px`;
}, 50);
});
</script>
<template lang="pug">
div(
@@ -214,5 +233,4 @@ div(
:category="category"
)
</template>
<style lang="sass">
</style>
<style lang="sass"></style>
@@ -1,177 +1,206 @@
<script setup lang="ts">
import { computed, ref, watch, onMounted, onUnmounted, inject, nextTick } from 'vue'
import { StoreKey } from '~/sharedStore'
import { STRINGS } from '~/i18n'
import {
computed,
ref,
watch,
onMounted,
onUnmounted,
inject,
nextTick,
} from "vue";
import { StoreKey } from "~/sharedStore";
import { STRINGS } from "~/i18n";
const store = inject(StoreKey)!
const store = inject(StoreKey)!;
const cancelBlocked = ref(false)
const lightboxImage = ref<HTMLImageElement>()
const frameDialog = ref<HTMLDialogElement>()
const alertDialog = ref<HTMLDialogElement>()
const lightboxDialog = ref<HTMLDialogElement>()
const iframe = ref<HTMLIFrameElement>()
const closeButton = ref<HTMLButtonElement>()
const cancelBlocked = ref(false);
const lightboxImage = ref<HTMLImageElement>();
const frameDialog = ref<HTMLDialogElement>();
const alertDialog = ref<HTMLDialogElement>();
const lightboxDialog = ref<HTMLDialogElement>();
const iframe = ref<HTMLIFrameElement>();
const closeButton = ref<HTMLButtonElement>();
const frameClasses = computed(() => ({
'pretix-widget-frame-holder': true,
'pretix-widget-frame-shown': store.overlay.frameShown || store.overlay.frameLoading,
'pretix-widget-frame-isloading': store.overlay.frameLoading,
}))
"pretix-widget-frame-holder": true,
"pretix-widget-frame-shown":
store.overlay.frameShown || store.overlay.frameLoading,
"pretix-widget-frame-isloading": store.overlay.frameLoading,
}));
const alertClasses = computed(() => ({
'pretix-widget-alert-holder': true,
'pretix-widget-alert-shown': store.overlay.errorMessage,
}))
"pretix-widget-alert-holder": true,
"pretix-widget-alert-shown": store.overlay.errorMessage,
}));
const lightboxClasses = computed(() => ({
'pretix-widget-lightbox-holder': true,
'pretix-widget-lightbox-shown': store.overlay.lightbox,
'pretix-widget-lightbox-isloading': store.overlay.lightbox?.loading,
}))
"pretix-widget-lightbox-holder": true,
"pretix-widget-lightbox-shown": store.overlay.lightbox,
"pretix-widget-lightbox-isloading": store.overlay.lightbox?.loading,
}));
const cancelBlockedClasses = computed(() => ({
'pretix-widget-visibility-hidden': !cancelBlocked.value,
}))
"pretix-widget-visibility-hidden": !cancelBlocked.value,
}));
const errorMessageId = computed(() => `${store.htmlId}-error-message`)
const errorMessageId = computed(() => `${store.htmlId}-error-message`);
function onMessage (e: MessageEvent) {
if (e.data.type && e.data.type === 'pretix:widget:title') {
function onMessage(e: MessageEvent) {
if (e.data.type && e.data.type === "pretix:widget:title") {
if (iframe.value) {
iframe.value.title = e.data.title
iframe.value.title = e.data.title;
}
}
}
function lightboxClose () {
store.overlay.lightbox = null
function lightboxClose() {
store.overlay.lightbox = null;
}
function lightboxLoaded () {
function lightboxLoaded() {
if (store.overlay.lightbox) {
store.overlay.lightbox.loading = false
store.overlay.lightbox.loading = false;
}
}
function errorContinue () {
function errorContinue() {
if (store.overlay.errorUrlAfterNewTab) {
window.open(store.overlay.errorUrlAfter)
window.open(store.overlay.errorUrlAfter);
} else {
store.overlay.frameSrc = store.overlay.errorUrlAfter
store.overlay.frameLoading = true
store.overlay.frameSrc = store.overlay.errorUrlAfter;
store.overlay.frameLoading = true;
}
}
function errorClose () {
store.overlay.errorMessage = null
store.overlay.errorUrlAfter = null
store.overlay.errorUrlAfterNewTab = false
function errorClose() {
store.overlay.errorMessage = null;
store.overlay.errorUrlAfter = null;
store.overlay.errorUrlAfterNewTab = false;
}
function close (e) {
function close(e) {
if (store.overlay.frameLoading) {
// Chrome does not allow blocking dialog.cancel event more than once
// => wiggle the loading-element and re-open the modal
cancel(e)
frameDialog.value?.showModal()
return
cancel(e);
frameDialog.value?.showModal();
return;
}
store.overlay.frameShown = false
store.frameDismissed = true
store.overlay.frameSrc = ''
store.reload()
triggerCloseCallback()
store.overlay.frameShown = false;
store.frameDismissed = true;
store.overlay.frameSrc = "";
store.reload();
triggerCloseCallback();
}
function cancel (e: Event) {
function cancel(e: Event) {
// do not allow to cancel while frame is loading as we cannot abort the operation
if (store.overlay.frameLoading) {
e.preventDefault()
const target = e.target as HTMLElement
target.addEventListener('animationend', function () {
target.classList.remove('pretix-widget-shake-once')
}, { once: true })
target.classList.add('pretix-widget-shake-once')
cancelBlocked.value = true
e.preventDefault();
const target = e.target as HTMLElement;
target.addEventListener(
"animationend",
function () {
target.classList.remove("pretix-widget-shake-once");
},
{ once: true },
);
target.classList.add("pretix-widget-shake-once");
cancelBlocked.value = true;
}
}
function iframeLoaded () {
function iframeLoaded() {
if (store.overlay.frameLoading) {
store.overlay.frameLoading = false
cancelBlocked.value = false
store.overlay.frameLoading = false;
cancelBlocked.value = false;
if (store.overlay.frameSrc) {
store.overlay.frameShown = true
store.overlay.frameShown = true;
}
}
}
function triggerCloseCallback () {
function triggerCloseCallback() {
nextTick(() => {
for (const callback of (window as any).PretixWidget._closed || []) {
callback()
callback();
}
})
});
}
// TODO check if watchEffect is better for the following watchers
watch(() => store.overlay.lightbox, (newValue, oldValue) => {
if (!newValue) return
if (newValue.image !== oldValue?.image) {
newValue.loading = true
}
if (!oldValue) {
lightboxDialog.value?.showModal()
}
})
watch(() => store.overlay.errorMessage, (newValue, oldValue) => {
if (newValue && !oldValue) {
alertDialog.value?.showModal()
}
})
watch(() => store.overlay.frameShown, async (newValue) => {
if (!newValue) return
await nextTick()
closeButton.value?.focus()
})
watch(() => store.overlay.frameSrc, (newValue, oldValue) => {
// show loading spinner only when previously no frame_src was set
if (newValue && !oldValue) {
store.overlay.frameLoading = true
}
if (iframe.value) {
// to close and unload the iframe, frame_src can be empty -> make it valid HTML with about:blank
iframe.value.src = newValue || 'about:blank'
}
})
watch(() => store.overlay.frameLoading, (newValue) => {
if (newValue) {
if (frameDialog.value && !frameDialog.value.open) {
frameDialog.value.showModal()
watch(
() => store.overlay.lightbox,
(newValue, oldValue) => {
if (!newValue) return;
if (newValue.image !== oldValue?.image) {
newValue.loading = true;
}
} else {
if (!store.overlay.frameSrc && frameDialog.value?.open) { // finished loading, but no iframe to display => close
frameDialog.value.close()
if (!oldValue) {
lightboxDialog.value?.showModal();
}
}
})
},
);
watch(
() => store.overlay.errorMessage,
(newValue, oldValue) => {
if (newValue && !oldValue) {
alertDialog.value?.showModal();
}
},
);
watch(
() => store.overlay.frameShown,
async (newValue) => {
if (!newValue) return;
await nextTick();
closeButton.value?.focus();
},
);
watch(
() => store.overlay.frameSrc,
(newValue, oldValue) => {
// show loading spinner only when previously no frame_src was set
if (newValue && !oldValue) {
store.overlay.frameLoading = true;
}
if (iframe.value) {
// to close and unload the iframe, frame_src can be empty -> make it valid HTML with about:blank
iframe.value.src = newValue || "about:blank";
}
},
);
watch(
() => store.overlay.frameLoading,
(newValue) => {
if (newValue) {
if (frameDialog.value && !frameDialog.value.open) {
frameDialog.value.showModal();
}
} else {
if (!store.overlay.frameSrc && frameDialog.value?.open) {
// finished loading, but no iframe to display => close
frameDialog.value.close();
}
}
},
);
onMounted(() => {
window.addEventListener('message', onMessage, false)
})
window.addEventListener("message", onMessage, false);
});
onUnmounted(() => {
window.removeEventListener('message', onMessage, false)
})
window.removeEventListener("message", onMessage, false);
});
const vAutofocus = {
mounted: (el) => el.focus()
}
mounted: (el) => el.focus(),
};
</script>
<template lang="pug">
@@ -231,5 +260,4 @@ Teleport(to="body")
)
figcaption(v-if="store.overlay.lightbox.description") {{ store.overlay.lightbox.description }}
</template>
<style lang="sass">
</style>
<style lang="sass"></style>
Loaded 100 of 119 files, more files were not shown because too many files have changed in this diff. Show more