mirror of
https://github.com/pretix/pretix.git
synced 2026-11-23 03:21:55 +00:00
Compare commits
108
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b1b2f1250b | ||
|
|
8a21c47be3 | ||
|
|
bed1cdead4 | ||
|
|
fbbcd8b613 | ||
|
|
d754ce643d | ||
|
|
0b371d104a | ||
|
|
45a609d73c | ||
|
|
46503f9494 | ||
|
|
c1c4bf13ea | ||
|
|
68991b3c0e | ||
|
|
da97a9099f | ||
|
|
0e0f74f2a5 | ||
|
|
8c8e844e6a | ||
|
|
c602aaa538 | ||
|
|
52235ff82c | ||
|
|
ac55ce2bcd | ||
|
|
8678a9d42a | ||
|
|
d49f97a6b7 | ||
|
|
65b5bb26ae | ||
|
|
47f92de4c3 | ||
|
|
435236fdde | ||
|
|
9e77f8dc59 | ||
|
|
58b3a60fae | ||
|
|
035421c3e1 | ||
|
|
b7bf4274d5 | ||
|
|
34e7a08b20 | ||
|
|
6660c4884e | ||
|
|
69624cc50c | ||
|
|
a3bdb2d1ee | ||
|
|
f4ace717a6 | ||
|
|
b3aa0066e8 | ||
|
|
dd485bda21 | ||
|
|
f1408adfa7 | ||
|
|
b70a91722f | ||
|
|
1b4f440107 | ||
|
|
0c1866c5e0 | ||
|
|
b3981974e2 | ||
|
|
430145a197 | ||
|
|
65233438df | ||
|
|
6f5e0ec396 | ||
|
|
4b92f9356a | ||
|
|
6989e4a6a0 | ||
|
|
e0f2215bca | ||
|
|
ec358c7784 | ||
|
|
2020346fb3 | ||
|
|
05813e9d5b | ||
|
|
19e05c68de | ||
|
|
5a6e0fe082 | ||
|
|
40454a3228 | ||
|
|
7e58fe2fe2 | ||
|
|
7279580eb4 | ||
|
|
c7d8ea91ff | ||
|
|
d965b3e0a8 | ||
|
|
a99cd42267 | ||
|
|
53614849c0 | ||
|
|
33bc96d215 | ||
|
|
74cb095c70 | ||
|
|
bfa1bdcf2c | ||
|
|
8511968063 | ||
|
|
dbc0f4a696 | ||
|
|
77fefc122b | ||
|
|
9185c8ef04 | ||
|
|
973a658714 | ||
|
|
67ae4b2ff9 | ||
|
|
903d444179 | ||
|
|
c4172245e0 | ||
|
|
61568fc71b | ||
|
|
24861c0fad | ||
|
|
9cb0e2c7a2 | ||
|
|
d5415cef1f | ||
|
|
b4574a7df2 | ||
|
|
2ca8e93f3b | ||
|
|
c4b4a28453 | ||
|
|
a49a395cc3 | ||
|
|
6e76405b79 | ||
|
|
89091ffb87 | ||
|
|
1b2adf9947 | ||
|
|
59ef58e33d | ||
|
|
dc87febe5e | ||
|
|
7303f90e86 | ||
|
|
1d9528e314 | ||
|
|
5aca40bb6c | ||
|
|
71a878bfa6 | ||
|
|
1724df924e | ||
|
|
165a205796 | ||
|
|
72d65d3a76 | ||
|
|
ac6d2b48e8 | ||
|
|
015c5f95b6 | ||
|
|
5b69fd1f07 | ||
|
|
e8be1d22f2 | ||
|
|
dcbcde349d | ||
|
|
db90fbd3a2 | ||
|
|
eaee4c5e00 | ||
|
|
c2a11f1c92 | ||
|
|
3eb2ad45d6 | ||
|
|
e77a943ea3 | ||
|
|
b56099fdeb | ||
|
|
a0278aba5c | ||
|
|
8b52346f2c | ||
|
|
49d175f691 | ||
|
|
5b6ad72767 | ||
|
|
87c24b9291 | ||
|
|
3132b79306 | ||
|
|
903a63c642 | ||
|
|
0322fe1d21 | ||
|
|
63f7b4915f | ||
|
|
e3ce54d51d | ||
|
|
e4592d7132 |
No files matched your search
@@ -7,6 +7,7 @@ on:
|
||||
- 'src/pretix/static/pretixpresale/widget/**'
|
||||
- 'src/pretix/static/pretixcontrol/js/ui/checkinrules/**'
|
||||
- 'src/pretix/plugins/webcheckin/**'
|
||||
- 'src/pretix/plugins/wallet/**'
|
||||
- 'eslint.config.mjs'
|
||||
- 'package.json'
|
||||
- 'package-lock.json'
|
||||
@@ -16,6 +17,7 @@ on:
|
||||
- 'src/pretix/static/pretixpresale/widget/**'
|
||||
- 'src/pretix/static/pretixcontrol/js/ui/checkinrules/**'
|
||||
- 'src/pretix/plugins/webcheckin/**'
|
||||
- 'src/pretix/plugins/wallet/**'
|
||||
- 'eslint.config.mjs'
|
||||
- 'package.json'
|
||||
- 'package-lock.json'
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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": {}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ we generally use a custom ``form_valid`` method on our ``FormView`` that looks l
|
||||
def form_valid(self, form):
|
||||
if form.has_changed():
|
||||
self.request.event.log_action('pretix.event.changed', user=self.request.user, data={
|
||||
k: getattr(self.request.event, k) for k in form.changed_data
|
||||
k: form.cleaned_data.get(k) for k in form.changed_data
|
||||
})
|
||||
messages.success(self.request, _('Your changes have been saved.'))
|
||||
return super().form_valid(form)
|
||||
|
||||
@@ -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,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
|
||||
|
||||
+7
-1
@@ -55,7 +55,7 @@ const ignores = globalIgnores([
|
||||
'src/pretix/static/pretixpresale/js/ui/cart.js',
|
||||
'src/pretix/static/pretixpresale/js/ui/main.js',
|
||||
'src/pretix/static/pretixpresale/js/ui/questions.js',
|
||||
'src/pretix/static/pretixpresale/js/widget/floatformat.js',
|
||||
'src/pretix/static/pretixpresale/js/floatformat.js',
|
||||
'src/pretix/static/pretixpresale/js/widget/widget.js',
|
||||
'src/pretix/plugins/banktransfer/static',
|
||||
'src/pretix/plugins/paypal2/static',
|
||||
@@ -161,4 +161,10 @@ export default defineConfig([
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/*.{vue,ts,tsx,mts,cts}'],
|
||||
rules: {
|
||||
'no-undef': 'off',
|
||||
},
|
||||
},
|
||||
])
|
||||
Generated
+127
@@ -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",
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@
|
||||
"build": "npm run build:control -s && npm run build:widget -s",
|
||||
"build:control": "vite build",
|
||||
"build:widget": "vite build src/pretix/static/pretixpresale/widget",
|
||||
"lint:eslint": "eslint src/pretix/static/pretixpresale/widget src/pretix/static/pretixcontrol/js/ui/checkinrules src/pretix/plugins/webcheckin",
|
||||
"lint:eslint": "eslint src/pretix/static/pretixbase/components src/pretix/static/pretixpresale/widget src/pretix/static/pretixcontrol/wallet src/pretix/static/pretixcontrol/js/ui/checkinrules src/pretix/plugins/webcheckin src/pretix/plugins/wallet",
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
+8
-6
@@ -34,7 +34,7 @@ dependencies = [
|
||||
"celery==5.6.*",
|
||||
"chardet==5.2.*",
|
||||
"cryptography>=50.0.2",
|
||||
"css-inline==0.24.*",
|
||||
"css-inline==0.23.*",
|
||||
"defusedcsv>=3.0.0",
|
||||
"dnspython==2.9.*",
|
||||
"Django[argon2]==5.2.*,>=5.2.17",
|
||||
@@ -60,9 +60,11 @@ dependencies = [
|
||||
"djangorestframework>=3.18.3",
|
||||
"drf_ujson2==1.7.*",
|
||||
"geoip2==5.*",
|
||||
"google-auth==2.62.*",
|
||||
"httpx==0.28.*",
|
||||
"isoweek",
|
||||
"jsonschema",
|
||||
"kombu==5.7.*",
|
||||
"kombu==5.6.*",
|
||||
"libsass==0.23.*",
|
||||
"lxml",
|
||||
"markdown==3.11.2",
|
||||
@@ -81,7 +83,8 @@ dependencies = [
|
||||
"pycountry",
|
||||
"pycparser==3.12",
|
||||
"pycryptodome==3.24.*",
|
||||
"pypdf==6.21.*",
|
||||
"pypdf==6.20.*",
|
||||
"python-bcp47 @ git+https://github.com/pretix/python-bcp47.git@v0.0.1",
|
||||
"python-bidi==0.6.*", # Support for Arabic in reportlab
|
||||
"python-dateutil==4.0.*",
|
||||
"pytz",
|
||||
@@ -91,7 +94,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 +126,7 @@ dev = [
|
||||
"pytest-sugar",
|
||||
"pytest-xdist==3.8.*",
|
||||
"pytest-playwright",
|
||||
"pytest-base-url",
|
||||
"pytest==9.2.*",
|
||||
"pytest==9.1.*",
|
||||
"playwright",
|
||||
"responses",
|
||||
"pypdfium2"
|
||||
|
||||
@@ -31,6 +31,7 @@ ignore =
|
||||
src/tests/plugins/stripe/*
|
||||
src/tests/plugins/sendmail/*
|
||||
src/tests/plugins/ticketoutputpdf/*
|
||||
src/tests/plugins/wallet/*
|
||||
.*
|
||||
CODE_OF_CONDUCT.md
|
||||
CONTRIBUTING.md
|
||||
|
||||
@@ -66,6 +66,8 @@ INSTALLED_APPS = [
|
||||
'pretix.plugins.returnurl',
|
||||
'pretix.plugins.autocheckin',
|
||||
'pretix.plugins.webcheckin',
|
||||
'pretix.plugins.apple_wallet',
|
||||
'pretix.plugins.google_wallet',
|
||||
'django_countries',
|
||||
'oauth2_provider',
|
||||
'phonenumber_field',
|
||||
|
||||
@@ -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'),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
from pretix.base.models import (
|
||||
CachedFile
|
||||
)
|
||||
from rest_framework.exceptions import ValidationError
|
||||
from django.core.exceptions import ValidationError as DjangoValidationError
|
||||
from django.conf import settings
|
||||
from pretix.api.auth.utils import get_session_key_for_api_auth
|
||||
|
||||
|
||||
def handle_file_upload(data, user, auth, allowed_types):
|
||||
try:
|
||||
cf = CachedFile.objects.get(
|
||||
file__isnull=False,
|
||||
pk=data[len("file:"):],
|
||||
)
|
||||
if cf.session_key == "api-upload-<class 'django.contrib.auth.models.AnonymousUser'>-None":
|
||||
# OK, backwards-compatibility of a security bug fixed 2026-09, delete this at some point, but should
|
||||
# also be harmless because all files with this key are expired one day after deployment of this fix
|
||||
# and no new files with this key are created
|
||||
pass
|
||||
elif cf.session_key != get_session_key_for_api_auth(user, auth):
|
||||
raise ValidationError('The submitted file ID "{fid}" was not found.'.format(fid=data))
|
||||
except (ValidationError, DjangoValidationError, IndexError): # invalid uuid
|
||||
raise ValidationError('The submitted file ID "{fid}" was not found.'.format(fid=data))
|
||||
except CachedFile.DoesNotExist:
|
||||
raise ValidationError('The submitted file ID "{fid}" was not found.'.format(fid=data))
|
||||
|
||||
if cf.type not in allowed_types:
|
||||
raise ValidationError('The submitted file "{fid}" has a file type that is not allowed in this field.'.format(fid=data))
|
||||
if cf.file.size > settings.FILE_UPLOAD_MAX_SIZE_OTHER:
|
||||
raise ValidationError('The submitted file "{fid}" is too large to be used in this field.'.format(fid=data))
|
||||
|
||||
return cf.file
|
||||
@@ -33,6 +33,7 @@
|
||||
# License for the specific language governing permissions and limitations under the License.
|
||||
|
||||
import logging
|
||||
import os.path
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import (
|
||||
@@ -65,6 +66,7 @@ from pretix.base.models.items import (
|
||||
ItemMetaProperty, SubEventItem, SubEventItemVariation,
|
||||
)
|
||||
from pretix.base.models.tax import CustomRulesValidator
|
||||
from pretix.base.models.wallet import WalletLayout, WalletPlatformLayout
|
||||
from pretix.base.plugins import (
|
||||
PLUGIN_LEVEL_EVENT, PLUGIN_LEVEL_EVENT_ORGANIZER_HYBRID,
|
||||
)
|
||||
@@ -76,6 +78,9 @@ from pretix.base.settings import (
|
||||
LazyI18nStringList, validate_event_settings,
|
||||
)
|
||||
from pretix.base.signals import api_event_settings_fields
|
||||
from pretix.base.wallet.platforms import (
|
||||
pass_style_registry, wallet_platform_registry,
|
||||
)
|
||||
from pretix.multidomain.urlreverse import eventreverse_absolute
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -805,6 +810,7 @@ class EventSettingsSerializer(SettingsSerializer):
|
||||
'ticket_download_nonadm',
|
||||
'ticket_download_pending',
|
||||
'ticket_download_require_validated_email',
|
||||
'ticket_wallet_enabled',
|
||||
'ticket_secret_length',
|
||||
'mail_prefix',
|
||||
'mail_from_name',
|
||||
@@ -962,6 +968,7 @@ class DeviceEventSettingsSerializer(EventSettingsSerializer):
|
||||
'ticket_download_addons',
|
||||
'ticket_download_nonadm',
|
||||
'ticket_download_pending',
|
||||
'ticket_wallet_enabled',
|
||||
'invoice_address_asked',
|
||||
'invoice_address_required',
|
||||
'invoice_address_vatid',
|
||||
@@ -1140,3 +1147,95 @@ class SeatSerializer(I18nAwareModelSerializer):
|
||||
from pretix.api.serializers.voucher import VoucherSerializer
|
||||
self.fields['voucher'] = VoucherSerializer(read_only=True)
|
||||
del self.fields['voucher'].fields['seat']
|
||||
|
||||
|
||||
class WalletPlatformLayoutSerializer(I18nAwareModelSerializer):
|
||||
platform = serializers.ChoiceField(choices=[])
|
||||
style = serializers.CharField(allow_null=True, required=False)
|
||||
file_settings = serializers.JSONField(default=dict, required=False)
|
||||
|
||||
class Meta:
|
||||
model = WalletPlatformLayout
|
||||
fields = ("platform", "style", "layout", "file_settings")
|
||||
|
||||
def get_fields(self):
|
||||
fields = super().get_fields()
|
||||
fields["platform"].choices = [
|
||||
p.identifier
|
||||
for p, _ in wallet_platform_registry.filter(active_in=self.context["event"])
|
||||
]
|
||||
return fields
|
||||
|
||||
def validate_layout(self, value):
|
||||
if not isinstance(value, dict):
|
||||
raise ValidationError(_("Layout must be a dict"))
|
||||
return value
|
||||
|
||||
def validate(self, data):
|
||||
platform = data.get("platform")
|
||||
style = data.get("style")
|
||||
layout = data.get("layout")
|
||||
if platform and style and layout:
|
||||
style, _meta = pass_style_registry.get(
|
||||
active_in=self.context["event"], identifier=(platform, style)
|
||||
)
|
||||
if not style:
|
||||
raise ValidationError({"style": _("Invalid style")})
|
||||
|
||||
obj = style(event=self.context["event"], layout=data["layout"])
|
||||
obj.validate()
|
||||
data["file_settings"] = obj.extract_file_settings(
|
||||
self.context["request"], data.get("file_settings", {})
|
||||
)
|
||||
|
||||
return data
|
||||
|
||||
def to_representation(self, instance):
|
||||
ret = super().to_representation(instance)
|
||||
ret["file_settings"] = {}
|
||||
for file_setting in instance.file_settings.all():
|
||||
try:
|
||||
url = file_setting.file.url
|
||||
except AttributeError:
|
||||
continue
|
||||
request = self.context["request"]
|
||||
ret["file_settings"][file_setting.key] = {
|
||||
"url": request.build_absolute_uri(url),
|
||||
"name": os.path.basename(file_setting.file.name).split(".", 1)[-1],
|
||||
}
|
||||
return ret
|
||||
|
||||
|
||||
class WalletLayoutSerializer(I18nAwareModelSerializer):
|
||||
platform_layouts = WalletPlatformLayoutSerializer(many=True)
|
||||
|
||||
class Meta:
|
||||
model = WalletLayout
|
||||
fields = ("id", "name", "platform_layouts")
|
||||
read_only_fields = ("id",)
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
super().save(*args, **kwargs, event=self.context["event"])
|
||||
|
||||
def update(self, instance, validated_data):
|
||||
platform_layouts = validated_data.pop("platform_layouts")
|
||||
for layout in platform_layouts:
|
||||
if layout["style"]:
|
||||
file_settings = layout.pop("file_settings", {})
|
||||
obj, _ = instance.platform_layouts.update_or_create(
|
||||
platform=layout["platform"], defaults=layout
|
||||
)
|
||||
obj.file_settings.exclude(key__in=file_settings.keys()).delete()
|
||||
for key, file in file_settings.items():
|
||||
if file != "keep":
|
||||
file_setting, _ = obj.file_settings.get_or_create(key=key)
|
||||
file_setting.file.save(os.path.basename(file.name), file)
|
||||
|
||||
instance.platform_layouts.exclude(
|
||||
platform__in={
|
||||
layout["platform"]
|
||||
for layout in platform_layouts
|
||||
if layout["style"] is not None
|
||||
}
|
||||
).delete()
|
||||
return super().update(instance, validated_data)
|
||||
@@ -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):
|
||||
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -100,6 +100,8 @@ event_router.register(r'scheduled_exports', exporters.ScheduledEventExportViewSe
|
||||
event_router.register(r'exporters', exporters.EventExportersViewSet, basename='exporters')
|
||||
event_router.register(r'shredders', shredders.EventShreddersViewSet, basename='shredders')
|
||||
event_router.register(r'item_meta_properties', event.ItemMetaPropertiesViewSet)
|
||||
event_router.register(r'walletlayouts', event.WalletLayoutViewSet)
|
||||
|
||||
|
||||
subevent_router = routers.DefaultRouter()
|
||||
subevent_router.register(r'seats', event.SeatViewSet)
|
||||
|
||||
@@ -64,7 +64,7 @@ from pretix.api.views import RichOrderingFilter
|
||||
from pretix.api.views.order import OrderPositionFilter
|
||||
from pretix.base.i18n import language
|
||||
from pretix.base.models import (
|
||||
CachedFile, Checkin, CheckinList, Device, Event, Order, OrderPosition,
|
||||
Checkin, CheckinList, Device, Event, Order, OrderPosition,
|
||||
Question, ReusableMedium, RevokedTicketSecret, TeamAPIToken,
|
||||
)
|
||||
from pretix.base.models.orders import PrintLog
|
||||
@@ -76,6 +76,7 @@ from pretix.base.services.checkin import (
|
||||
from pretix.base.services.media import perform_media_exchange
|
||||
from pretix.base.signals import checkin_annulled
|
||||
from pretix.helpers import OF_SELF
|
||||
from pretix.api.helpers import handle_file_upload
|
||||
|
||||
with scopes_disabled():
|
||||
class CheckinListFilter(FilterSet):
|
||||
@@ -329,35 +330,6 @@ with scopes_disabled():
|
||||
)
|
||||
|
||||
|
||||
def _handle_file_upload(data, user, auth):
|
||||
try:
|
||||
cf = CachedFile.objects.get(
|
||||
file__isnull=False,
|
||||
pk=data[len("file:"):],
|
||||
)
|
||||
if cf.session_key == "api-upload-<class 'django.contrib.auth.models.AnonymousUser'>-None":
|
||||
# OK, backwards-compatibility of a security bug fixed 2026-09, delete this at some point, but should
|
||||
# also be harmless because all files with this key are expired one day after deployment of this fix
|
||||
# and no new files with this key are created
|
||||
pass
|
||||
elif cf.session_key != get_session_key_for_api_auth(user, auth):
|
||||
raise ValidationError('The submitted file ID "{fid}" was not found.'.format(fid=data))
|
||||
except (ValidationError, BaseValidationError, IndexError): # invalid uuid
|
||||
raise ValidationError('The submitted file ID "{fid}" was not found.'.format(fid=data))
|
||||
except CachedFile.DoesNotExist:
|
||||
raise ValidationError('The submitted file ID "{fid}" was not found.'.format(fid=data))
|
||||
|
||||
allowed_types = (
|
||||
'image/png', 'image/jpeg', 'image/gif', 'application/pdf'
|
||||
)
|
||||
if cf.type not in allowed_types:
|
||||
raise ValidationError('The submitted file "{fid}" has a file type that is not allowed in this field.'.format(fid=data))
|
||||
if cf.file.size > settings.FILE_UPLOAD_MAX_SIZE_OTHER:
|
||||
raise ValidationError('The submitted file "{fid}" is too large to be used in this field.'.format(fid=data))
|
||||
|
||||
return cf.file
|
||||
|
||||
|
||||
def _checkin_list_position_queryset(checkinlists, ignore_status=False, ignore_products=False, pdf_data=False, expand=None):
|
||||
list_by_event = {cl.event_id: cl for cl in checkinlists}
|
||||
if not checkinlists:
|
||||
@@ -802,7 +774,12 @@ def _redeem_process(*, checkinlists, raw_barcode, answers_data, datetime, force,
|
||||
try:
|
||||
if q.type == Question.TYPE_FILE:
|
||||
if answers_data[str(q.pk)]:
|
||||
given_answers[q] = _handle_file_upload(answers_data[str(q.pk)], user, auth)
|
||||
given_answers[q] = handle_file_upload(
|
||||
answers_data[str(q.pk)],
|
||||
user,
|
||||
auth,
|
||||
allowed_types=('image/png', 'image/jpeg', 'image/gif', 'application/pdf')
|
||||
)
|
||||
else:
|
||||
given_answers[q] = None
|
||||
else:
|
||||
|
||||
@@ -54,7 +54,7 @@ from pretix.api.serializers.event import (
|
||||
CloneEventSerializer, DeviceEventSettingsSerializer, EventSerializer,
|
||||
EventSettingsSerializer, ItemMetaPropertiesSerializer,
|
||||
SeatBulkBlockInputSerializer, SeatSerializer, SubEventSerializer,
|
||||
TaxRuleSerializer,
|
||||
TaxRuleSerializer, WalletLayoutSerializer
|
||||
)
|
||||
from pretix.api.views import ConditionalListView
|
||||
from pretix.base.models import (
|
||||
@@ -62,7 +62,9 @@ from pretix.base.models import (
|
||||
TaxRule, TeamAPIToken,
|
||||
)
|
||||
from pretix.base.models.event import SubEvent
|
||||
from pretix.base.models.wallet import WalletLayout
|
||||
from pretix.base.services.quotas import QuotaAvailability
|
||||
from pretix.base.services import tickets
|
||||
from pretix.helpers.dicts import merge_dicts
|
||||
from pretix.helpers.i18n import i18ncomp
|
||||
from pretix.presale.views.organizer import filter_qs_by_attr
|
||||
@@ -797,3 +799,31 @@ class SeatViewSet(ConditionalListView, UpdateModelMixin, viewsets.ReadOnlyModelV
|
||||
@action(methods=["POST"], detail=False)
|
||||
def bulk_unblock(self, request, *args, **kwargs):
|
||||
return self.bulk_change_blocked(False)
|
||||
|
||||
|
||||
class WalletLayoutViewSet(viewsets.ModelViewSet):
|
||||
model = WalletLayout
|
||||
queryset = WalletLayout.objects.none()
|
||||
serializer_class = WalletLayoutSerializer
|
||||
permission = "event.settings.general:write"
|
||||
|
||||
def get_queryset(self):
|
||||
return self.request.event.wallet_layouts.all()
|
||||
|
||||
def get_serializer_context(self):
|
||||
ctx = super().get_serializer_context()
|
||||
ctx["event"] = self.request.event
|
||||
return ctx
|
||||
|
||||
@transaction.atomic()
|
||||
def perform_update(self, serializer):
|
||||
super().perform_update(serializer)
|
||||
serializer.instance.log_action(
|
||||
action="pretix.plugins.wallet.layout.changed",
|
||||
user=self.request.user,
|
||||
auth=self.request.auth,
|
||||
data=serializer.to_representation(serializer.instance),
|
||||
)
|
||||
tickets.invalidate_cache.apply_async(
|
||||
kwargs={"event": self.request.event.pk, "provider": "wallet"}
|
||||
)
|
||||
@@ -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()
|
||||
|
||||
@@ -653,8 +653,6 @@ class EventOrderViewSet(OrderViewSetMixin, viewsets.ModelViewSet):
|
||||
request.event, op, force_invalidate=True, save=True
|
||||
)
|
||||
order.save(update_fields=['secret'])
|
||||
CachedTicket.objects.filter(order_position__order=order).delete()
|
||||
CachedCombinedTicket.objects.filter(order=order).delete()
|
||||
tickets.invalidate_cache.apply_async(kwargs={'event': self.request.event.pk,
|
||||
'order': order.pk})
|
||||
order.log_action(
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
#
|
||||
from datetime import timedelta
|
||||
|
||||
from celery.result import AsyncResult
|
||||
from django.conf import settings
|
||||
from django.http import Http404
|
||||
from django.shortcuts import get_object_or_404
|
||||
@@ -39,7 +40,6 @@ from pretix.api.serializers.shredders import (
|
||||
from pretix.base.models import CachedFile
|
||||
from pretix.base.services.shredder import export, shred
|
||||
from pretix.base.shredder import shred_constraints
|
||||
from pretix.helpers.celery import get_task_result
|
||||
from pretix.helpers.http import ChunkBasedFileResponse
|
||||
|
||||
|
||||
@@ -87,7 +87,7 @@ class ShreddersMixin:
|
||||
status=status.HTTP_410_GONE
|
||||
)
|
||||
|
||||
res = get_task_result(kwargs['asyncid'], task_name=export)
|
||||
res = AsyncResult(kwargs['asyncid'])
|
||||
if res.failed():
|
||||
if isinstance(res.info, dict) and res.info['exc_type'] in ('ShredError', 'ExportError'):
|
||||
msg = res.info['exc_message']
|
||||
@@ -108,7 +108,7 @@ class ShreddersMixin:
|
||||
@action(detail=False, methods=['GET'], url_name='status', url_path='status/(?P<asyncid>[^/]+)/(?P<cfid>[^/]+)')
|
||||
def status(self, *args, **kwargs):
|
||||
if settings.HAS_CELERY:
|
||||
res = get_task_result(kwargs['asyncid'], task_name=shred)
|
||||
res = AsyncResult(kwargs['asyncid'])
|
||||
if res.failed():
|
||||
if isinstance(res.info, dict) and res.info['exc_type'] in ('ShredError', 'ExportError'):
|
||||
msg = res.info['exc_message']
|
||||
@@ -141,17 +141,12 @@ class ShreddersMixin:
|
||||
status=status.HTTP_410_GONE
|
||||
)
|
||||
|
||||
if settings.HAS_CELERY:
|
||||
return Response(
|
||||
{
|
||||
'status': 'running' if res.state in ('PROGRESS', 'STARTED', 'SUCCESS') else 'waiting',
|
||||
},
|
||||
status=status.HTTP_409_CONFLICT
|
||||
)
|
||||
else:
|
||||
# This can't happen for clients who follow the api spec. They would need have to constructed the url themselves
|
||||
# from a valid shredder cached file, e.g. by modifying the URL retured by `export`.
|
||||
raise Http404()
|
||||
return Response(
|
||||
{
|
||||
'status': 'running' if res.state in ('PROGRESS', 'STARTED', 'SUCCESS') else 'waiting',
|
||||
},
|
||||
status=status.HTTP_409_CONFLICT
|
||||
)
|
||||
|
||||
@action(detail=False, methods=['POST'], url_name='shred', url_path='shred/(?P<asyncid>[^/]+)/(?P<cfid>[^/]+)')
|
||||
def shred(self, *args, **kwargs):
|
||||
@@ -168,10 +163,11 @@ class ShreddersMixin:
|
||||
raise Http404()
|
||||
if cf.file:
|
||||
async_result = self.do_shred(cf)
|
||||
url_kwargs = self.kwargs | {
|
||||
url_kwargs = {
|
||||
'asyncid': str(async_result.id),
|
||||
'cfid': str(cf.id),
|
||||
}
|
||||
url_kwargs.update(self.kwargs)
|
||||
return Response({
|
||||
'status': reverse('api-v1:shredders-status', kwargs=url_kwargs, request=self.request),
|
||||
}, status=status.HTTP_202_ACCEPTED)
|
||||
@@ -181,7 +177,7 @@ class ShreddersMixin:
|
||||
status=status.HTTP_410_GONE
|
||||
)
|
||||
|
||||
res = get_task_result(kwargs['asyncid'], task_name=export)
|
||||
res = AsyncResult(kwargs['asyncid'])
|
||||
if res.failed():
|
||||
if isinstance(res.info, dict) and res.info['exc_type'] in ('ShredError', 'ExportError'):
|
||||
msg = res.info['exc_message']
|
||||
|
||||
@@ -173,13 +173,11 @@ class UploadedFileWidget(forms.ClearableFileInput):
|
||||
|
||||
@property
|
||||
def url(self):
|
||||
from pretix.base.templatetags.safelink import answer_url
|
||||
|
||||
token = get_token(self.request, self.answer)
|
||||
if self.request.resolver_match.namespace == 'control':
|
||||
return self.answer.backend_file_url + '?token=' + token
|
||||
else:
|
||||
return answer_url(self.request, self.answer)
|
||||
return self.answer.frontend_file_url + '?token=' + token
|
||||
|
||||
def get_context(self, name, value, attrs):
|
||||
# Browsers can't recognize that the server already has a file uploaded
|
||||
|
||||
+66
-1
@@ -33,12 +33,14 @@
|
||||
# License for the specific language governing permissions and limitations under the License.
|
||||
|
||||
from contextlib import contextmanager
|
||||
from typing import Callable, Protocol, runtime_checkable
|
||||
|
||||
from asgiref.local import Local
|
||||
from babel import localedata
|
||||
from django.conf import settings
|
||||
from django.utils import translation
|
||||
from django.utils.formats import date_format, number_format
|
||||
from django.utils.functional import Promise
|
||||
from django.utils.translation import gettext
|
||||
|
||||
from i18nfield.fields import ( # noqa
|
||||
@@ -109,7 +111,7 @@ ALLOWED_LANGUAGES = dict(settings.LANGUAGES)
|
||||
|
||||
|
||||
def get_babel_locale():
|
||||
# Babel, and therefore also django-phonenumberfield, do not support our custom locales such das de_Informal
|
||||
# Babel, and therefore also django-phonenumberfield, do not support our custom locales such as de_Informal
|
||||
# Also, this returns best-effort region information for number formatting etc
|
||||
current_language = translation.get_language()
|
||||
current_region = getattr(_active_region, "value", None)
|
||||
@@ -204,3 +206,66 @@ class LazyLocaleException(Exception):
|
||||
return gettext(self.msg) % self.msgargs
|
||||
else:
|
||||
return gettext(self.msg)
|
||||
|
||||
|
||||
type MaybeTranslatedString = str | Localizable
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class Localizable(Protocol):
|
||||
def localize(self, lng: str) -> str: ... # noqa: E704
|
||||
|
||||
|
||||
# hack: marked Promise so DjangoJSONEncoder automatically transforms it into a string
|
||||
class LocalizableBase(Promise):
|
||||
"""
|
||||
Base for classes conforming to `Localizable` by implementing a language-aware __str__.
|
||||
"""
|
||||
def localize(self, lng):
|
||||
with translation.override(lng):
|
||||
return str(self)
|
||||
|
||||
|
||||
class FormattingLocalizableString(LocalizableBase):
|
||||
def __init__(
|
||||
self,
|
||||
base_str: MaybeTranslatedString,
|
||||
*format_args: MaybeTranslatedString,
|
||||
**format_kwargs: MaybeTranslatedString,
|
||||
):
|
||||
self.base_str = base_str
|
||||
self.format_args = format_args
|
||||
self.format_kwargs = format_kwargs
|
||||
|
||||
def __str__(self):
|
||||
return str(self.base_str).format(*self.format_args, **self.format_kwargs)
|
||||
|
||||
|
||||
class GettextLocalizableString(LocalizableBase):
|
||||
def __init__(self, base):
|
||||
self.base = base
|
||||
|
||||
@classmethod
|
||||
def gettext(cls, base):
|
||||
"""Fake function so makemessages picks up these strings."""
|
||||
return cls(base)
|
||||
|
||||
def __str__(self):
|
||||
return translation.gettext(self.base)
|
||||
|
||||
|
||||
class LocalizableDatetime(LocalizableBase):
|
||||
def __init__(self, datetime, format):
|
||||
self.datetime = datetime
|
||||
self.format = format
|
||||
|
||||
def __str__(self):
|
||||
return date_format(self.datetime, self.format)
|
||||
|
||||
|
||||
class LazyLocalizable(LocalizableBase):
|
||||
def __init__(self, func: Callable[..., str]):
|
||||
self.func = func
|
||||
|
||||
def __str__(self):
|
||||
return self.func()
|
||||
@@ -25,7 +25,7 @@ from django.utils.translation import gettext_lazy as _
|
||||
from django_countries.fields import Country
|
||||
|
||||
from pretix.base.models import Invoice
|
||||
from pretix.base.signals import EventPluginRegistry, Registry
|
||||
from pretix.base.signals import PluginAwareRegistry, Registry
|
||||
|
||||
|
||||
class TransmissionType:
|
||||
@@ -220,7 +220,7 @@ class TransmissionProvider:
|
||||
return None
|
||||
|
||||
|
||||
class TransmissionProviderRegistry(EventPluginRegistry):
|
||||
class TransmissionProviderRegistry(PluginAwareRegistry):
|
||||
def __init__(self):
|
||||
super().__init__({
|
||||
'identifier': lambda o: getattr(o, 'identifier'),
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
# Generated by Django 5.2.19 on 2026-11-12 12:06
|
||||
|
||||
import django.db.models.deletion
|
||||
import pretix.base.models.base
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
("pretixbase", "0311_fix_unshredded_invoices"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name="WalletLayout",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.BigAutoField(
|
||||
auto_created=True, primary_key=True, serialize=False
|
||||
),
|
||||
),
|
||||
("name", models.CharField(max_length=190)),
|
||||
("default", models.BooleanField(default=False)),
|
||||
(
|
||||
"event",
|
||||
models.ForeignKey(
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
related_name="wallet_layouts",
|
||||
to="pretixbase.event",
|
||||
),
|
||||
),
|
||||
],
|
||||
options={
|
||||
"ordering": ("-default", "name"),
|
||||
},
|
||||
bases=(models.Model, pretix.base.models.base.LoggingMixin),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name="WalletLayoutItem",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.BigAutoField(
|
||||
auto_created=True, primary_key=True, serialize=False
|
||||
),
|
||||
),
|
||||
(
|
||||
"item",
|
||||
models.OneToOneField(
|
||||
null=True,
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
related_name="walletlayout",
|
||||
to="pretixbase.item",
|
||||
),
|
||||
),
|
||||
(
|
||||
"layout",
|
||||
models.ForeignKey(
|
||||
null=True,
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
related_name="item_assignments",
|
||||
to="pretixbase.walletlayout",
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name="WalletPlatformLayout",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.BigAutoField(
|
||||
auto_created=True, primary_key=True, serialize=False
|
||||
),
|
||||
),
|
||||
("platform", models.CharField(max_length=10)),
|
||||
("style", models.CharField(max_length=255)),
|
||||
("layout", models.JSONField(default=dict)),
|
||||
(
|
||||
"parent",
|
||||
models.ForeignKey(
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
related_name="platform_layouts",
|
||||
to="pretixbase.walletlayout",
|
||||
),
|
||||
),
|
||||
],
|
||||
bases=(models.Model, pretix.base.models.base.LoggingMixin),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name="WalletLayoutFileSetting",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.BigAutoField(
|
||||
auto_created=True, primary_key=True, serialize=False
|
||||
),
|
||||
),
|
||||
("key", models.CharField()),
|
||||
("file", models.FileField(upload_to="")),
|
||||
(
|
||||
"layout",
|
||||
models.ForeignKey(
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
related_name="file_settings",
|
||||
to="pretixbase.walletplatformlayout",
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name="walletlayout",
|
||||
constraint=models.UniqueConstraint(
|
||||
models.F("event"),
|
||||
condition=models.Q(("default", True)),
|
||||
name="one_default_wallet_per_event",
|
||||
),
|
||||
),
|
||||
migrations.AlterUniqueTogether(
|
||||
name="walletplatformlayout",
|
||||
unique_together={("parent", "platform")},
|
||||
),
|
||||
]
|
||||
@@ -24,6 +24,7 @@ import uuid
|
||||
|
||||
from django.contrib.contenttypes.models import ContentType
|
||||
from django.db import models
|
||||
from django.db.models.constants import LOOKUP_SEP
|
||||
from django.db.models.signals import post_delete
|
||||
from django.dispatch import receiver
|
||||
from django.urls import reverse
|
||||
@@ -244,3 +245,49 @@ class LoggedModel(models.Model, LoggingMixin):
|
||||
return LogEntry.objects.filter(
|
||||
content_type=self.logs_content_type, object_id=self.pk
|
||||
).select_related('user', 'event', 'event__organizer', 'oauth_application', 'api_token', 'device')
|
||||
|
||||
|
||||
class LockModel:
|
||||
def refresh_for_update(self, fields=None, using=None, **kwargs):
|
||||
"""
|
||||
Like refresh_from_db(), but with select_for_update().
|
||||
See also https://code.djangoproject.com/ticket/28344
|
||||
"""
|
||||
if fields is not None:
|
||||
if not fields:
|
||||
return
|
||||
if any(LOOKUP_SEP in f for f in fields):
|
||||
raise ValueError(
|
||||
'Found "%s" in fields argument. Relations and transforms '
|
||||
'are not allowed in fields.' % LOOKUP_SEP)
|
||||
|
||||
hints = {'instance': self}
|
||||
db_instance_qs = self.__class__._base_manager.db_manager(using, hints=hints).filter(pk=self.pk).select_for_update(**kwargs)
|
||||
|
||||
# Use provided fields, if not set then reload all non-deferred fields.
|
||||
deferred_fields = self.get_deferred_fields()
|
||||
if fields is not None:
|
||||
fields = list(fields)
|
||||
db_instance_qs = db_instance_qs.only(*fields)
|
||||
elif deferred_fields:
|
||||
fields = [f.attname for f in self._meta.concrete_fields
|
||||
if f.attname not in deferred_fields]
|
||||
db_instance_qs = db_instance_qs.only(*fields)
|
||||
|
||||
db_instance = db_instance_qs.get()
|
||||
non_loaded_fields = db_instance.get_deferred_fields()
|
||||
for field in self._meta.concrete_fields:
|
||||
if field.attname in non_loaded_fields:
|
||||
# This field wasn't refreshed - skip ahead.
|
||||
continue
|
||||
setattr(self, field.attname, getattr(db_instance, field.attname))
|
||||
# Clear cached foreign keys.
|
||||
if field.is_relation and field.is_cached(self):
|
||||
field.delete_cached_value(self)
|
||||
|
||||
# Clear cached relations.
|
||||
for field in self._meta.related_objects:
|
||||
if field.is_cached(self):
|
||||
field.delete_cached_value(self)
|
||||
|
||||
self._state.db = db_instance._state.db
|
||||
@@ -93,7 +93,7 @@ class Gate(LoggedModel):
|
||||
if instance:
|
||||
qs = qs.exclude(pk=instance.pk)
|
||||
if qs.exists():
|
||||
raise ValidationError(_('This identifier is already used for a different gate.'))
|
||||
raise ValidationError(_('This identifier is already used for a different question.'))
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
if not self.identifier:
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
#
|
||||
# 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/>.
|
||||
#
|
||||
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.db import models
|
||||
from django.db.models import Q, constraints
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from django_scopes import ScopedManager
|
||||
|
||||
from pretix.base.models import LoggedModel
|
||||
|
||||
|
||||
class WalletLayout(LoggedModel):
|
||||
event = models.ForeignKey(
|
||||
"pretixbase.Event", on_delete=models.CASCADE, related_name="wallet_layouts"
|
||||
)
|
||||
name = models.CharField(max_length=190, verbose_name=_("Name"))
|
||||
default = models.BooleanField(
|
||||
verbose_name=_("Default"),
|
||||
default=False,
|
||||
)
|
||||
|
||||
objects = ScopedManager(organizer="event__organizer")
|
||||
|
||||
class Meta:
|
||||
constraints = [
|
||||
constraints.UniqueConstraint(
|
||||
"event", condition=Q(default=True), name="one_default_wallet_per_event"
|
||||
)
|
||||
]
|
||||
ordering = (
|
||||
"-default",
|
||||
"name",
|
||||
)
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
|
||||
def allow_delete(self):
|
||||
return not self.default
|
||||
|
||||
|
||||
class WalletPlatformLayout(LoggedModel):
|
||||
parent = models.ForeignKey(
|
||||
WalletLayout, on_delete=models.CASCADE, related_name="platform_layouts"
|
||||
)
|
||||
|
||||
platform = models.CharField(max_length=10)
|
||||
style = models.CharField(max_length=255)
|
||||
layout = models.JSONField(default=dict)
|
||||
|
||||
objects = ScopedManager(organizer="parent__event__organizer")
|
||||
|
||||
class Meta:
|
||||
unique_together = (("parent", "platform"),)
|
||||
|
||||
@property
|
||||
def pass_layout(self):
|
||||
from ...base.wallet.platforms import pass_style_registry
|
||||
|
||||
style, _meta = pass_style_registry.get(active_in=self.parent.event, identifier=(self.platform, self.style))
|
||||
if style:
|
||||
file_settings = {fs.key: fs.file for fs in self.file_settings.all()}
|
||||
return style(
|
||||
event=self.parent.event, layout=self.layout, file_settings=file_settings
|
||||
)
|
||||
else:
|
||||
raise ValueError(f"Style {self.platform}.{self.style} not found")
|
||||
|
||||
|
||||
class WalletLayoutItem(models.Model):
|
||||
item = models.OneToOneField(
|
||||
"pretixbase.Item",
|
||||
null=True,
|
||||
blank=True,
|
||||
related_name="walletlayout",
|
||||
on_delete=models.CASCADE,
|
||||
)
|
||||
layout = models.ForeignKey(
|
||||
WalletLayout,
|
||||
null=True,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="item_assignments",
|
||||
)
|
||||
|
||||
def clean(self):
|
||||
if self.layout and self.item.event != self.layout.event:
|
||||
raise ValidationError("cannot bind layout to item of different event")
|
||||
|
||||
|
||||
class WalletLayoutFileSetting(models.Model):
|
||||
layout = models.ForeignKey(
|
||||
WalletPlatformLayout, on_delete=models.CASCADE, related_name="file_settings"
|
||||
)
|
||||
key = models.CharField()
|
||||
file = models.FileField()
|
||||
@@ -21,21 +21,30 @@
|
||||
#
|
||||
import logging
|
||||
import os
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from decimal import Decimal
|
||||
|
||||
from django.core.files.base import ContentFile
|
||||
from django.db import transaction
|
||||
from django.utils.timezone import now
|
||||
from django.utils.translation import gettext as _
|
||||
from django_scopes import scopes_disabled
|
||||
from i18nfield.strings import LazyI18nString
|
||||
|
||||
from pretix.base.i18n import language
|
||||
from pretix.base.models import (
|
||||
CachedCombinedTicket, CachedTicket, Event, InvoiceAddress, Order,
|
||||
OrderPosition,
|
||||
)
|
||||
from pretix.base.services.tasks import EventTask, ProfiledTask
|
||||
from pretix.base.services.tasks import (
|
||||
ProfiledTask, TransactionAwareProfiledEventTask,
|
||||
)
|
||||
from pretix.base.settings import PERSON_NAME_SCHEMES
|
||||
from pretix.base.signals import register_ticket_outputs
|
||||
from pretix.base.signals import (
|
||||
invalidate_ticket_cache, register_ticket_outputs,
|
||||
)
|
||||
from pretix.base.wallet.platforms import get_available_platforms
|
||||
from pretix.celery_app import app
|
||||
from pretix.helpers.database import rolledback_transaction
|
||||
|
||||
@@ -52,6 +61,7 @@ def generate_orderposition(order_position: int, provider: str):
|
||||
if prov.identifier == provider:
|
||||
filename, ttype, data = prov.generate(order_position)
|
||||
path, ext = os.path.splitext(filename)
|
||||
|
||||
for ct in CachedTicket.objects.filter(order_position=order_position, provider=provider):
|
||||
ct.delete()
|
||||
ct = CachedTicket.objects.create(order_position=order_position, provider=provider,
|
||||
@@ -70,6 +80,7 @@ def generate_order(order: int, provider: str):
|
||||
if prov.identifier == provider:
|
||||
filename, ttype, data = prov.generate_order(order)
|
||||
path, ext = os.path.splitext(filename)
|
||||
|
||||
for ct in CachedCombinedTicket.objects.filter(order=order, provider=provider):
|
||||
ct.delete()
|
||||
ct = CachedCombinedTicket.objects.create(order=order, provider=provider, extension=ext,
|
||||
@@ -91,35 +102,55 @@ class DummyRollbackException(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def preview(event: int, provider: str):
|
||||
def get_preview_position(event):
|
||||
connection = transaction.get_connection()
|
||||
if not connection.in_atomic_block:
|
||||
raise RuntimeError("get_preview_position needs to be called in a rolledback_transaction")
|
||||
|
||||
item = event.items.create(name=LazyI18nString.from_gettext("Sample product"), default_price=Decimal('42.23'),
|
||||
description=LazyI18nString.from_gettext("Sample product description"))
|
||||
item2 = event.items.create(name=LazyI18nString.from_gettext("Sample workshop"), default_price=Decimal('23.40'))
|
||||
item.program_times.create(item=item, start=datetime(2017, 12, 27, 0, 0, 0, tzinfo=timezone.utc),
|
||||
end=datetime(2017, 12, 28, 0, 0, 0, tzinfo=timezone.utc))
|
||||
|
||||
from pretix.base.models import Order, SeatingPlan
|
||||
order = event.orders.create(status=Order.STATUS_PENDING, datetime=now(),
|
||||
email='sample@pretix.eu',
|
||||
locale=event.settings.locale,
|
||||
sales_channel=event.organizer.sales_channels.get(identifier="web"),
|
||||
expires=now(), code="PREVIEW1234", total=119)
|
||||
|
||||
scheme = PERSON_NAME_SCHEMES[event.settings.name_scheme]
|
||||
sample = {k: str(v) for k, v in scheme['sample'].items()}
|
||||
|
||||
SeatingPlan.objects.create(
|
||||
name="Plan", organizer=event.organizer, layout="{}"
|
||||
)
|
||||
event.seat_category_mappings.create(
|
||||
layout_category='Stalls', product=item
|
||||
)
|
||||
seat = event.seats.create(seat_number="1", row_label="C", product=item, seat_guid=uuid.uuid4())
|
||||
|
||||
position = order.positions.create(item=item, attendee_name_parts=sample, price=item.default_price, seat=seat)
|
||||
s = event.subevents.first()
|
||||
order.positions.create(item=item2, attendee_name_parts=sample, price=item.default_price, addon_to=position, subevent=s)
|
||||
order.positions.create(item=item2, attendee_name_parts=sample, price=item.default_price, addon_to=position, subevent=s)
|
||||
|
||||
InvoiceAddress.objects.create(order=order, name_parts=sample, company=_("Sample company"))
|
||||
return position
|
||||
|
||||
|
||||
def preview(event: int, provider: str, provider_arguments: dict = {}):
|
||||
event = Event.objects.get(id=event)
|
||||
|
||||
with rolledback_transaction(), language(event.settings.locale, event.settings.region):
|
||||
item = event.items.create(name=_("Sample product"), default_price=Decimal('42.23'),
|
||||
description=_("Sample product description"))
|
||||
item2 = event.items.create(name=_("Sample workshop"), default_price=Decimal('23.40'))
|
||||
|
||||
from pretix.base.models import Order
|
||||
order = event.orders.create(status=Order.STATUS_PENDING, datetime=now(),
|
||||
email='sample@pretix.eu',
|
||||
locale=event.settings.locale,
|
||||
sales_channel=event.organizer.sales_channels.get(identifier="web"),
|
||||
expires=now(), code="PREVIEW1234", total=119)
|
||||
|
||||
scheme = PERSON_NAME_SCHEMES[event.settings.name_scheme]
|
||||
sample = {k: str(v) for k, v in scheme['sample'].items()}
|
||||
p = order.positions.create(item=item, attendee_name_parts=sample, price=item.default_price)
|
||||
s = event.subevents.first()
|
||||
order.positions.create(item=item2, attendee_name_parts=sample, price=item.default_price, addon_to=p, subevent=s)
|
||||
order.positions.create(item=item2, attendee_name_parts=sample, price=item.default_price, addon_to=p, subevent=s)
|
||||
|
||||
InvoiceAddress.objects.create(order=order, name_parts=sample, company=_("Sample company"))
|
||||
p = get_preview_position(event)
|
||||
|
||||
responses = register_ticket_outputs.send(event)
|
||||
for receiver, response in responses:
|
||||
prov = response(event)
|
||||
if prov.identifier == provider:
|
||||
return prov.generate(p)
|
||||
return prov.generate(p, **provider_arguments)
|
||||
|
||||
|
||||
def get_tickets_for_order(order, base_position=None):
|
||||
@@ -206,8 +237,8 @@ def get_tickets_for_order(order, base_position=None):
|
||||
return tickets
|
||||
|
||||
|
||||
@app.task(base=EventTask, acks_late=True)
|
||||
def invalidate_cache(event: Event, item: int=None, provider: str=None, order: int=None, **kwargs):
|
||||
@app.task(base=TransactionAwareProfiledEventTask, acks_late=True)
|
||||
def invalidate_cache(event: Event, item: int | None=None, provider: str | None=None, order: int | None=None, **kwargs):
|
||||
qs = CachedTicket.objects.filter(order_position__order__event=event)
|
||||
qsc = CachedCombinedTicket.objects.filter(order__event=event)
|
||||
|
||||
@@ -226,3 +257,43 @@ def invalidate_cache(event: Event, item: int=None, provider: str=None, order: in
|
||||
ct.delete()
|
||||
for ct in qsc:
|
||||
ct.delete()
|
||||
|
||||
invalidate_ticket_cache.send(event, item=item, provider=provider, order=order)
|
||||
|
||||
|
||||
def get_download_buttons(event, show_disabled):
|
||||
buttons = []
|
||||
|
||||
responses = register_ticket_outputs.send(event)
|
||||
for receiver, response in responses:
|
||||
provider = response(event)
|
||||
if not provider.is_enabled and not show_disabled:
|
||||
continue
|
||||
buttons.append({
|
||||
'text': provider.download_button_text or 'Download',
|
||||
'multi_text': provider.multi_download_button_text or 'Download',
|
||||
'long_text': provider.long_download_button_text or 'Download',
|
||||
'icon': provider.download_button_icon or 'fa-download',
|
||||
'identifier': provider.identifier,
|
||||
'multi': provider.multi_download_enabled,
|
||||
'javascript_required': provider.javascript_required,
|
||||
})
|
||||
return buttons
|
||||
|
||||
|
||||
def get_wallet_buttons(event: Event, positions: list[OrderPosition], show_disabled: bool):
|
||||
platforms = list(get_available_platforms(event, show_disabled))
|
||||
|
||||
buttons: dict[str | OrderPosition, list] = {"combined": []}
|
||||
for platform in platforms:
|
||||
if any(platform.is_available_for_position(pos) for pos in positions):
|
||||
attr, cont = platform.render_download_button()
|
||||
buttons["combined"].append({"identifier": platform.identifier, "attributes": attr, "content": cont})
|
||||
|
||||
for position in positions:
|
||||
buttons[position] = []
|
||||
for platform in platforms:
|
||||
if platform.is_available_for_position(position):
|
||||
attr, cont = platform.render_download_button()
|
||||
buttons[position].append({"identifier": platform.identifier, "attributes": attr, "content": cont})
|
||||
return buttons
|
||||
@@ -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(
|
||||
@@ -1873,6 +1872,16 @@ DEFAULTS = {
|
||||
"the email. Does not affect orders performed through other sales channels."),
|
||||
)
|
||||
},
|
||||
'ticket_wallet_enabled': {
|
||||
'default': 'False',
|
||||
'type': bool,
|
||||
'serializer_class': serializers.BooleanField,
|
||||
'form_class': forms.BooleanField,
|
||||
'form_kwargs': dict(
|
||||
label=_("Generate wallet passes"),
|
||||
help_text=_('If this is off, no wallet passes will be generated.'),
|
||||
)
|
||||
},
|
||||
'low_availability_percentage': {
|
||||
'default': None,
|
||||
'type': int,
|
||||
|
||||
+47
-16
@@ -34,7 +34,7 @@
|
||||
|
||||
import logging
|
||||
import warnings
|
||||
from typing import Any, Callable, Generic, List, Tuple, TypeVar
|
||||
from typing import Any, Callable, Generic, Iterable, List, Tuple, TypeVar
|
||||
|
||||
import django.dispatch
|
||||
from django.apps import apps
|
||||
@@ -440,7 +440,8 @@ class Registry:
|
||||
meta = {k: accessor(obj) for k, accessor in self.keys.items()}
|
||||
tup = (obj, meta)
|
||||
for key, value in meta.items():
|
||||
self.by_key[key][value] = tup
|
||||
self.by_key[key].setdefault(value, [])
|
||||
self.by_key[key][value].append(tup)
|
||||
self.registered_entries[obj] = meta
|
||||
|
||||
if len(objs) == 1:
|
||||
@@ -465,16 +466,33 @@ class Registry:
|
||||
return clz
|
||||
return reg
|
||||
|
||||
def get(self, **kwargs):
|
||||
(key, value), = kwargs.items()
|
||||
return self.by_key.get(key).get(value, (None, None))
|
||||
def get(self, **kwargs) -> tuple[Any, dict[str, Any]] | tuple[None, None]:
|
||||
result = list(self.filter(**kwargs))
|
||||
|
||||
def filter(self, **kwargs):
|
||||
return (
|
||||
(entry, meta)
|
||||
for entry, meta in self.registered_entries.items()
|
||||
if all(value == meta[key] for key, value in kwargs.items())
|
||||
)
|
||||
if len(result) == 1:
|
||||
return result[0]
|
||||
elif len(result) >= 1:
|
||||
raise RuntimeError(f"get() returned more than one -- it returned {len(result)}!")
|
||||
return (None, None)
|
||||
|
||||
def filter(self, **kwargs) -> Iterable[tuple[Any, dict[str, Any]]]:
|
||||
for key in kwargs.keys():
|
||||
if key not in self.keys:
|
||||
raise ValueError(f"Unknown key: {key!r}")
|
||||
|
||||
if len(kwargs) == 1:
|
||||
# fast route: lookup using `self.by_key`
|
||||
(key, value), = kwargs.items()
|
||||
return self.by_key.get(key, {}).get(value, [])
|
||||
else:
|
||||
return (
|
||||
(entry, meta)
|
||||
for entry, meta in self.registered_entries.items()
|
||||
if all(value == meta[key] for key, value in kwargs.items())
|
||||
)
|
||||
|
||||
def all(self):
|
||||
return self.registered_entries.keys()
|
||||
|
||||
|
||||
class PluginAwareRegistry(Registry):
|
||||
@@ -522,11 +540,7 @@ class PluginAwareRegistry(Registry):
|
||||
return result
|
||||
|
||||
def get(self, active_in=None, **kwargs):
|
||||
item, meta = super().get(**kwargs)
|
||||
if meta and active_in is not None:
|
||||
if not is_app_active(active_in, meta['plugin']):
|
||||
return None, None
|
||||
return item, meta
|
||||
return super().get(active_in=active_in, **kwargs)
|
||||
|
||||
|
||||
EventPluginRegistry = PluginAwareRegistry # for backwards compatibility
|
||||
@@ -1218,3 +1232,20 @@ This signal is sent out each time the information for a Device is modified.
|
||||
Both the original and updated versions of the Device are included to allow
|
||||
receivers to see what has been updated.
|
||||
"""
|
||||
|
||||
register_wallet_placeholders = EventPluginSignal()
|
||||
"""
|
||||
This signal is sent out to get all known wallet placeholders. Receivers should return
|
||||
an list of subclasses of pretix.base.wallet.placeholders.BaseWalletPlaceholder.
|
||||
|
||||
As with all event-plugin signals, the ``sender`` keyword argument will contain the event.
|
||||
"""
|
||||
|
||||
invalidate_ticket_cache = EventPluginSignal()
|
||||
"""
|
||||
Arguments: ``item: int | None``, ``provider: str | None``, ``order: int | None``
|
||||
|
||||
This signal is sent out when the ticket cache is invalidated.
|
||||
|
||||
As with all event-plugin signals, the ``sender`` keyword argument will contain the event.
|
||||
"""
|
||||
@@ -0,0 +1 @@
|
||||
{% for key, value in attributes.items %}{% if key != "class" %}{% if value is not False %} {{ key }}{% if value is not True %}="{{ value|stringformat:'s' }}"{% endif %}{% endif %}{% endif %}{% endfor %}
|
||||
@@ -36,10 +36,10 @@ register = template.Library()
|
||||
|
||||
|
||||
@register.filter("money")
|
||||
def money_filter(value: Optional[Decimal | float | int | str], arg='', hide_currency=False):
|
||||
def money_filter(value: Optional[Decimal | float | int | str], arg='', hide_currency=False) -> str:
|
||||
if isinstance(value, (float, int, str)):
|
||||
if value == '':
|
||||
return value
|
||||
return value # pyright: ignore[reportReturnType]
|
||||
value = Decimal(value)
|
||||
if value is None:
|
||||
value = Decimal('0.00')
|
||||
|
||||
@@ -340,14 +340,7 @@ class LinkifyAndCleanExtension(Extension):
|
||||
)
|
||||
|
||||
|
||||
class SnippetExtension(markdown.extensions.Extension):
|
||||
def extendMarkdown(self, md, *args, **kwargs):
|
||||
md.parser.blockprocessors.deregister('olist')
|
||||
md.parser.blockprocessors.deregister('ulist')
|
||||
md.parser.blockprocessors.deregister('quote')
|
||||
|
||||
|
||||
def _get_email_markdown(allowed_tags=None, allowed_attributes=ALLOWED_ATTRIBUTES, snippet=False, context=None):
|
||||
def markdown_compile_email(source, allowed_tags=None, allowed_attributes=ALLOWED_ATTRIBUTES, snippet=False, context=None):
|
||||
if allowed_tags is None:
|
||||
allowed_tags = ALLOWED_TAGS_SNIPPET if snippet else ALLOWED_TAGS
|
||||
|
||||
@@ -388,16 +381,20 @@ def _get_email_markdown(allowed_tags=None, allowed_attributes=ALLOWED_ATTRIBUTES
|
||||
]
|
||||
if snippet:
|
||||
exts.append(SnippetExtension())
|
||||
|
||||
return markdown.Markdown(extensions=exts)
|
||||
return markdown.markdown(
|
||||
source,
|
||||
extensions=exts
|
||||
)
|
||||
|
||||
|
||||
def markdown_compile_email(source, allowed_tags=None, allowed_attributes=ALLOWED_ATTRIBUTES, snippet=False, context=None):
|
||||
md = _get_email_markdown(allowed_tags, allowed_attributes, snippet, context)
|
||||
return md.convert(source)
|
||||
class SnippetExtension(markdown.extensions.Extension):
|
||||
def extendMarkdown(self, md, *args, **kwargs):
|
||||
md.parser.blockprocessors.deregister('olist')
|
||||
md.parser.blockprocessors.deregister('ulist')
|
||||
md.parser.blockprocessors.deregister('quote')
|
||||
|
||||
|
||||
def _get_markdown(linker, snippet=False):
|
||||
def markdown_compile(source, linker, snippet=False):
|
||||
tags = ALLOWED_TAGS_SNIPPET if snippet else ALLOWED_TAGS
|
||||
exts = [
|
||||
'markdown.extensions.sane_lists',
|
||||
@@ -412,13 +409,10 @@ def _get_markdown(linker, snippet=False):
|
||||
]
|
||||
if snippet:
|
||||
exts.append(SnippetExtension())
|
||||
|
||||
return markdown.Markdown(extensions=exts)
|
||||
|
||||
|
||||
def markdown_compile(source, linker, snippet=False):
|
||||
md = _get_markdown(linker, snippet)
|
||||
return md.convert(source)
|
||||
return markdown.markdown(
|
||||
source,
|
||||
extensions=exts
|
||||
)
|
||||
|
||||
|
||||
@register.filter
|
||||
@@ -451,25 +445,3 @@ def rich_text_snippet(text: str, **kwargs):
|
||||
)
|
||||
body_md = markdown_compile(text, linker, snippet=True)
|
||||
return mark_safe(body_md)
|
||||
|
||||
|
||||
def _md_escape(md: markdown.Markdown, plain: str):
|
||||
escaped_chars = md.ESCAPED_CHARS
|
||||
translation_map = {ord(x): f"\\{x}" for x in escaped_chars}
|
||||
return plain.translate(translation_map)
|
||||
|
||||
|
||||
def markdown_escape(plain: str) -> str:
|
||||
"""
|
||||
Escape formatting characters in markdown with backslash using the default markdown renderer config.
|
||||
"""
|
||||
md = _get_markdown(bleach.Linker())
|
||||
return _md_escape(md, plain)
|
||||
|
||||
|
||||
def markdown_email_escape(plain: str) -> str:
|
||||
"""
|
||||
Escape formatting characters in markdown with backslash using the default email markdown renderer config.
|
||||
"""
|
||||
md = _get_email_markdown(None, False)
|
||||
return _md_escape(md, plain)
|
||||
@@ -22,7 +22,6 @@
|
||||
from django import template
|
||||
|
||||
from pretix.helpers.safedownload import get_token
|
||||
from pretix.multidomain.urlreverse import eventreverse
|
||||
|
||||
from ..views.redirect import safelink as sl
|
||||
|
||||
@@ -37,19 +36,3 @@ def safelink(url):
|
||||
@register.simple_tag
|
||||
def answer_token(request, answer):
|
||||
return get_token(request, answer)
|
||||
|
||||
|
||||
@register.simple_tag
|
||||
def answer_url(request, answer):
|
||||
if answer.file:
|
||||
if answer.associated_order:
|
||||
url = eventreverse(answer.associated_order.event, 'presale:event.download.answer', kwargs={
|
||||
'answer': answer.pk,
|
||||
})
|
||||
else:
|
||||
url = eventreverse(request.event, 'presale:event.cart.download.answer', kwargs={
|
||||
'answer': answer.pk,
|
||||
})
|
||||
|
||||
return url + "?token=" + get_token(request, answer)
|
||||
return ""
|
||||
@@ -99,7 +99,7 @@ class BaseTicketOutput:
|
||||
def get_tickets_to_print(self, order):
|
||||
return order.positions_with_tickets
|
||||
|
||||
def generate_order(self, order: Order) -> Tuple[str, str, str]:
|
||||
def generate_order(self, order: Order) -> Tuple[str, str, str | bytes]:
|
||||
"""
|
||||
This method is the same as order() but should not generate one file per order position
|
||||
but instead one file for the full order.
|
||||
@@ -114,7 +114,7 @@ class BaseTicketOutput:
|
||||
If you override this method, make sure that positions that are addons (i.e. ``addon_to``
|
||||
is set) are only outputted if the event setting ``ticket_download_addons`` is active.
|
||||
Do the same for positions that are non-admission without ``ticket_download_nonadm`` active.
|
||||
If you want, you can just iterate over ``order.positions_with_tickets`` which applies the
|
||||
If you want, you can just iterate over ``self.get_tickets_to_print`` which applies the
|
||||
appropriate filters for you.
|
||||
"""
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
|
||||
@@ -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')
|
||||
@@ -58,14 +57,10 @@ RE_ASYNC_ID = re.compile(r"^[a-zA-Z0-9\-]+$")
|
||||
|
||||
|
||||
class AsyncMixin:
|
||||
success_url = None
|
||||
error_url = None
|
||||
success_url: str | None = None
|
||||
error_url: str | None = 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)
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
from . import base, placeholders
|
||||
from .base import WalletPlaceholderRenderer, get_available_context
|
||||
from .placeholders import (
|
||||
get_wallet_placeholder_renderer, get_wallet_placeholders,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"base",
|
||||
"placeholders",
|
||||
"get_available_context",
|
||||
"get_wallet_placeholder_renderer",
|
||||
"get_wallet_placeholders",
|
||||
"WalletPlaceholderRenderer",
|
||||
]
|
||||
@@ -0,0 +1,302 @@
|
||||
from collections.abc import Callable
|
||||
from functools import cached_property
|
||||
from typing import Any
|
||||
|
||||
from django.core.files import File
|
||||
|
||||
from pretix.base.i18n import MaybeTranslatedString
|
||||
|
||||
|
||||
class BaseWalletPlaceholder:
|
||||
"""
|
||||
This is the base class for all wallet placeholders.
|
||||
"""
|
||||
|
||||
@property
|
||||
def required_context(self) -> set[str]:
|
||||
"""
|
||||
A a set of all attribute names that need to be contained in the base context so that this placeholder is available.
|
||||
"""
|
||||
return set()
|
||||
|
||||
@property
|
||||
def identifier(self) -> str:
|
||||
"""The unique identifier of this placeholder"""
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def content_type(self) -> str:
|
||||
"""The content type this placeholder generates (text / image)"""
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def label(self) -> MaybeTranslatedString:
|
||||
"""The human readable name of this placeholder"""
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def control_label(self) -> MaybeTranslatedString:
|
||||
"""
|
||||
The human readable name of this placeholder shown in the backend.
|
||||
|
||||
Defaults to `label`
|
||||
"""
|
||||
return self.label
|
||||
|
||||
def render(self, **context):
|
||||
raise NotImplementedError()
|
||||
|
||||
def render_sample(self, **context):
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
class BaseWalletTextPlaceholder(BaseWalletPlaceholder):
|
||||
@property
|
||||
def content_type(self) -> str:
|
||||
return "text"
|
||||
|
||||
def render(self, **context) -> MaybeTranslatedString | None:
|
||||
"""
|
||||
This method is called to generate the text that is being shown on the pass.
|
||||
You will be passed the keyword arguments specified in ``required_context``.
|
||||
You are expected to return a plain-text string.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def render_sample(self, **context) -> MaybeTranslatedString:
|
||||
"""
|
||||
This method is called to generate a text to be used in previews.
|
||||
|
||||
You will be passed sample instances of the arguments specified in ``required_context``.
|
||||
If those instances contain all data needed, you do not need to implement this.
|
||||
"""
|
||||
sample = self.render(**context)
|
||||
if not sample:
|
||||
raise RuntimeError("`render` returned falsy value when rendering a sample")
|
||||
return sample
|
||||
|
||||
|
||||
class BaseWalletImagePlaceholder(BaseWalletPlaceholder):
|
||||
@property
|
||||
def content_type(self) -> str:
|
||||
return "image"
|
||||
|
||||
def render(self, **context) -> File | None:
|
||||
"""
|
||||
This method is called to generate the image that is being shown on the pass.
|
||||
You will be passed the keyword arguments specified in ``required_context``.
|
||||
You are expected to return a `File` object.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def render_sample(self, **context) -> str | None:
|
||||
"""
|
||||
This method is called to generate a text to be used in previews.
|
||||
|
||||
You will be passed sample instances of the arguments specified in ``required_context``.
|
||||
You are expected to return a URL to a sample image or `None` if no sample can be shown.
|
||||
"""
|
||||
return None
|
||||
|
||||
|
||||
class FunctionalWalletTextPlaceholder(BaseWalletTextPlaceholder):
|
||||
def __init__(
|
||||
self,
|
||||
identifier: str,
|
||||
label: MaybeTranslatedString,
|
||||
args: set[str],
|
||||
func: Callable[..., MaybeTranslatedString | None],
|
||||
sample: (
|
||||
None | MaybeTranslatedString | Callable[..., MaybeTranslatedString]
|
||||
) = None,
|
||||
):
|
||||
self._identifier = identifier
|
||||
self._label = label
|
||||
self._args = args
|
||||
self.render = func
|
||||
self._sample = sample
|
||||
|
||||
def __repr__(self):
|
||||
return f"FunctionalWalletTextPlaceholder(identifier={self.identifier!r}, label={self.label!r})"
|
||||
|
||||
@property
|
||||
def identifier(self):
|
||||
return self._identifier
|
||||
|
||||
@property
|
||||
def label(self):
|
||||
return self._label
|
||||
|
||||
@property
|
||||
def required_context(self) -> set[str]:
|
||||
return self._args
|
||||
|
||||
def render_sample(self, **context) -> MaybeTranslatedString:
|
||||
if isinstance(self._sample, Callable):
|
||||
return self._sample(**context)
|
||||
elif self._sample:
|
||||
return self._sample
|
||||
else:
|
||||
return super().render_sample(**context)
|
||||
|
||||
|
||||
class FunctionalWalletImagePlaceholder(BaseWalletImagePlaceholder):
|
||||
def __init__(
|
||||
self,
|
||||
identifier: str,
|
||||
label: MaybeTranslatedString,
|
||||
args: set[str],
|
||||
func: Callable[..., File | None],
|
||||
sample: None | str | Callable[..., str] = None,
|
||||
):
|
||||
self._identifier = identifier
|
||||
self._label = label
|
||||
self._args = args
|
||||
self.render = func
|
||||
self._sample = sample
|
||||
|
||||
@property
|
||||
def required_context(self) -> set[str]:
|
||||
return self._args
|
||||
|
||||
@property
|
||||
def identifier(self):
|
||||
return self._identifier
|
||||
|
||||
@property
|
||||
def label(self):
|
||||
return self._label
|
||||
|
||||
def render_sample(self, **context) -> str | None:
|
||||
if isinstance(self._sample, Callable):
|
||||
return self._sample(**context)
|
||||
return self._sample
|
||||
|
||||
|
||||
class MissingContextException(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class PlaceholderContextTransformation:
|
||||
@property
|
||||
def required_context(self) -> set[str]:
|
||||
"""
|
||||
A a set of all attribute names that need to be contained in the base context for this transformation to function.
|
||||
"""
|
||||
return set()
|
||||
|
||||
@property
|
||||
def generated_context_name(self) -> str:
|
||||
"""The name of the context arg this transformation produces"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def transform(self, context):
|
||||
raise NotImplementedError("`transform` not implemented")
|
||||
|
||||
|
||||
class FunctionalContextTransformation(PlaceholderContextTransformation):
|
||||
def __init__(self, context_name: str, context_args: set[str], func: Callable):
|
||||
self.context_args = context_args
|
||||
self.context_name = context_name
|
||||
self.transform = func
|
||||
|
||||
@property
|
||||
def required_context(self) -> set[str]:
|
||||
return self.context_args
|
||||
|
||||
@property
|
||||
def generated_context_name(self) -> str:
|
||||
return self.context_name
|
||||
|
||||
|
||||
def get_available_context(
|
||||
initial_context: set[str], transformations: list[PlaceholderContextTransformation]
|
||||
):
|
||||
used_trans = set()
|
||||
available_context = set(initial_context)
|
||||
changed = True
|
||||
while changed:
|
||||
changed = False
|
||||
for trans in transformations:
|
||||
if trans in used_trans:
|
||||
continue
|
||||
|
||||
if trans.required_context <= available_context:
|
||||
used_trans.add(trans)
|
||||
if trans.generated_context_name not in available_context:
|
||||
available_context.add(trans.generated_context_name)
|
||||
changed = True
|
||||
|
||||
return available_context
|
||||
|
||||
|
||||
def get_transformed_context(
|
||||
context_args: dict[str, Any],
|
||||
transformations: list[PlaceholderContextTransformation],
|
||||
):
|
||||
used_trans = set()
|
||||
transformed_context_args = dict(context_args)
|
||||
changed = True
|
||||
while changed:
|
||||
changed = False
|
||||
for trans in transformations:
|
||||
if trans in used_trans:
|
||||
continue
|
||||
|
||||
if trans.required_context <= transformed_context_args.keys():
|
||||
used_trans.add(trans)
|
||||
if trans.generated_context_name not in transformed_context_args.keys():
|
||||
transformation_context = {
|
||||
k: v
|
||||
for k, v in transformed_context_args.items()
|
||||
if k in trans.required_context
|
||||
}
|
||||
transformed_context_args[trans.generated_context_name] = (
|
||||
trans.transform(**transformation_context)
|
||||
)
|
||||
changed = True
|
||||
|
||||
return transformed_context_args
|
||||
|
||||
|
||||
class WalletPlaceholderRenderer:
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
transformations: list[PlaceholderContextTransformation] | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
self.context = kwargs
|
||||
self.cache = {}
|
||||
self.transformations = list(transformations) if transformations else []
|
||||
|
||||
@cached_property
|
||||
def _get_transformed_context(self):
|
||||
return get_transformed_context(self.context, self.transformations)
|
||||
|
||||
def _get_placeholder_context(self, placeholder: BaseWalletPlaceholder):
|
||||
context = self._get_transformed_context
|
||||
missing_context = placeholder.required_context - context.keys()
|
||||
if missing_context:
|
||||
raise MissingContextException(
|
||||
f"Missing context args for '{placeholder.identifier}': {', '.join(missing_context)}"
|
||||
)
|
||||
|
||||
return {k: v for k, v in context.items() if k in placeholder.required_context}
|
||||
|
||||
def is_available(self, placeholder: BaseWalletPlaceholder, context_args: set[str]):
|
||||
available_context = get_available_context(context_args, self.transformations)
|
||||
missing_context = placeholder.required_context - available_context
|
||||
return not missing_context
|
||||
|
||||
def render_placeholder(self, placeholder: BaseWalletPlaceholder):
|
||||
if placeholder.identifier in self.cache:
|
||||
return self.cache[placeholder.identifier]
|
||||
|
||||
value = self.cache[placeholder.identifier] = placeholder.render(
|
||||
**self._get_placeholder_context(placeholder)
|
||||
)
|
||||
return value
|
||||
|
||||
def render_sample(self, placeholder: BaseWalletPlaceholder):
|
||||
return placeholder.render_sample(**self._get_placeholder_context(placeholder))
|
||||
@@ -0,0 +1,296 @@
|
||||
from django.contrib.staticfiles import finders
|
||||
from django.core.files import File
|
||||
from django.dispatch import receiver
|
||||
|
||||
from pretix.base.i18n import (
|
||||
FormattingLocalizableString, GettextLocalizableString, LocalizableDatetime,
|
||||
)
|
||||
from pretix.base.models.event import Event
|
||||
from pretix.base.signals import register_wallet_placeholders
|
||||
from pretix.base.templatetags.money import money_filter
|
||||
from pretix.multidomain.urlreverse import eventreverse_absolute
|
||||
|
||||
from .base import (
|
||||
BaseWalletPlaceholder, FunctionalContextTransformation,
|
||||
FunctionalWalletTextPlaceholder, WalletPlaceholderRenderer,
|
||||
)
|
||||
|
||||
|
||||
def get_wallet_placeholder_renderer(**kwargs):
|
||||
return WalletPlaceholderRenderer(
|
||||
**kwargs,
|
||||
transformations=[
|
||||
# TODO: make this extendable via signal?
|
||||
FunctionalContextTransformation(
|
||||
"item", {"order_position"}, lambda order_position: order_position.item
|
||||
),
|
||||
FunctionalContextTransformation(
|
||||
"order", {"order_position"}, lambda order_position: order_position.order
|
||||
),
|
||||
FunctionalContextTransformation(
|
||||
"event", {"order"}, lambda order: order.event
|
||||
),
|
||||
FunctionalContextTransformation(
|
||||
"organizer", {"event"}, lambda event: event.organizer
|
||||
),
|
||||
FunctionalContextTransformation(
|
||||
"subevent_or_event",
|
||||
{"order_position"},
|
||||
lambda order_position: order_position.subevent
|
||||
or order_position.order.event,
|
||||
),
|
||||
FunctionalContextTransformation(
|
||||
"seat",
|
||||
{"order_position"},
|
||||
lambda order_position: (
|
||||
order_position.seat if order_position.seat_id else None
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def get_wallet_placeholders(event) -> dict[str, dict[str, BaseWalletPlaceholder]]:
|
||||
placeholders = {"text": {}, "image": {}}
|
||||
for r, ps in register_wallet_placeholders.send(sender=event):
|
||||
for placeholder in ps:
|
||||
placeholders[placeholder.content_type][placeholder.identifier] = placeholder
|
||||
return placeholders
|
||||
|
||||
|
||||
def get_static_file(name) -> File | None:
|
||||
path: str | None = finders.find(name) # type: ignore
|
||||
if not path:
|
||||
return
|
||||
return File(open(path, "rb"))
|
||||
|
||||
|
||||
def admission(subevent_or_event):
|
||||
return (
|
||||
LocalizableDatetime(
|
||||
subevent_or_event.date_admission.astimezone(subevent_or_event.timezone),
|
||||
"SHORT_DATETIME_FORMAT",
|
||||
)
|
||||
if subevent_or_event.date_admission
|
||||
else None
|
||||
)
|
||||
|
||||
|
||||
def date_from(subevent_or_event):
|
||||
return LocalizableDatetime(
|
||||
subevent_or_event.date_from.astimezone(subevent_or_event.timezone),
|
||||
"SHORT_DATETIME_FORMAT",
|
||||
)
|
||||
|
||||
|
||||
def admission_or_date_from(subevent_or_event):
|
||||
return admission(subevent_or_event) or date_from(subevent_or_event)
|
||||
|
||||
|
||||
def website(order_position, order):
|
||||
if order_position.subevent:
|
||||
return eventreverse_absolute(
|
||||
order.event,
|
||||
"presale:event.index",
|
||||
{"subevent": order_position.subevent.pk},
|
||||
)
|
||||
else:
|
||||
return eventreverse_absolute(order.event, "presale:event.index")
|
||||
|
||||
|
||||
@receiver(
|
||||
register_wallet_placeholders,
|
||||
dispatch_uid="plugin_wallet_register_wallet_placeholders",
|
||||
)
|
||||
def base_text_placeholders(sender: Event, **kwargs):
|
||||
return [
|
||||
FunctionalWalletTextPlaceholder(
|
||||
"event",
|
||||
GettextLocalizableString.gettext("Event"),
|
||||
{"event"},
|
||||
lambda event: event.name,
|
||||
),
|
||||
FunctionalWalletTextPlaceholder(
|
||||
"event_slug",
|
||||
GettextLocalizableString.gettext("Event Slug"),
|
||||
{"event"},
|
||||
lambda event: event.slug,
|
||||
),
|
||||
FunctionalWalletTextPlaceholder(
|
||||
"admission",
|
||||
GettextLocalizableString.gettext("Admission"),
|
||||
{"subevent_or_event"},
|
||||
admission,
|
||||
date_from,
|
||||
),
|
||||
FunctionalWalletTextPlaceholder(
|
||||
"date_from",
|
||||
GettextLocalizableString.gettext("Begin"),
|
||||
{"subevent_or_event"},
|
||||
date_from,
|
||||
),
|
||||
FunctionalWalletTextPlaceholder(
|
||||
"admission_or_date_from",
|
||||
GettextLocalizableString.gettext("Admission or Date From"),
|
||||
{"subevent_or_event"},
|
||||
admission_or_date_from,
|
||||
),
|
||||
FunctionalWalletTextPlaceholder(
|
||||
"order",
|
||||
GettextLocalizableString.gettext("Order Code"),
|
||||
{"order"},
|
||||
lambda order: order.code,
|
||||
),
|
||||
FunctionalWalletTextPlaceholder(
|
||||
"total",
|
||||
GettextLocalizableString.gettext("Order Total"),
|
||||
{"event", "order"},
|
||||
lambda event, order: money_filter(order.total, event.currency),
|
||||
),
|
||||
FunctionalWalletTextPlaceholder(
|
||||
"order_email",
|
||||
GettextLocalizableString.gettext("Order Email"),
|
||||
{"order"},
|
||||
lambda order: order.email,
|
||||
),
|
||||
FunctionalWalletTextPlaceholder(
|
||||
"price",
|
||||
GettextLocalizableString.gettext("Item Price"),
|
||||
{"event", "order_position"},
|
||||
lambda event, order_position: money_filter(
|
||||
order_position.price, event.currency
|
||||
),
|
||||
),
|
||||
FunctionalWalletTextPlaceholder(
|
||||
"secret",
|
||||
GettextLocalizableString.gettext("Order Secret (QR-Code-Content)"),
|
||||
{"order_position"},
|
||||
lambda order_position: order_position.secret,
|
||||
),
|
||||
FunctionalWalletTextPlaceholder(
|
||||
"item",
|
||||
GettextLocalizableString.gettext("Product"),
|
||||
{"item"},
|
||||
lambda item: item.name,
|
||||
),
|
||||
FunctionalWalletTextPlaceholder(
|
||||
"item_description",
|
||||
GettextLocalizableString.gettext("Product description"),
|
||||
{"item"},
|
||||
lambda item: item.description,
|
||||
),
|
||||
FunctionalWalletTextPlaceholder(
|
||||
"item_with_variation",
|
||||
GettextLocalizableString.gettext("Product and variation"),
|
||||
{"order_position"},
|
||||
lambda order_position: (
|
||||
FormattingLocalizableString(
|
||||
"{name} - {variation}",
|
||||
name=order_position.item.name,
|
||||
variation=order_position.variation.value,
|
||||
)
|
||||
if order_position.variation
|
||||
else order_position.item.name
|
||||
),
|
||||
),
|
||||
FunctionalWalletTextPlaceholder(
|
||||
"seat",
|
||||
GettextLocalizableString.gettext("Seat: Full name"),
|
||||
{"seat"},
|
||||
lambda seat: (
|
||||
FormattingLocalizableString("{seat}", seat=seat) if seat else None
|
||||
),
|
||||
GettextLocalizableString.gettext("Ground floor, Row 3, Seat 4"),
|
||||
),
|
||||
FunctionalWalletTextPlaceholder(
|
||||
"seat_zone",
|
||||
GettextLocalizableString.gettext("Seat: Zone"),
|
||||
{"seat"},
|
||||
lambda seat: seat.zone_name,
|
||||
GettextLocalizableString.gettext("Ground floor"),
|
||||
),
|
||||
FunctionalWalletTextPlaceholder(
|
||||
"seat_row",
|
||||
GettextLocalizableString.gettext("Seat: Row"),
|
||||
{"seat"},
|
||||
lambda seat: seat.row_label or seat.row_name,
|
||||
"C",
|
||||
),
|
||||
FunctionalWalletTextPlaceholder(
|
||||
"seat_number",
|
||||
GettextLocalizableString.gettext("Seat: Seat Number"),
|
||||
{"seat"},
|
||||
lambda seat: seat.seat_label or seat.seat_number,
|
||||
"5",
|
||||
),
|
||||
FunctionalWalletTextPlaceholder(
|
||||
"attendee_name",
|
||||
GettextLocalizableString.gettext("Attendee name"),
|
||||
{"order_position"},
|
||||
lambda order_position: order_position.attendee_name,
|
||||
),
|
||||
FunctionalWalletTextPlaceholder(
|
||||
"program_start",
|
||||
GettextLocalizableString.gettext("Programm times: Start"),
|
||||
{"item", "subevent_or_event"},
|
||||
lambda item, subevent_or_event: (
|
||||
LocalizableDatetime(
|
||||
min(pt.start for pt in item.program_times.all()).astimezone(
|
||||
subevent_or_event.timezone
|
||||
),
|
||||
"SHORT_DATETIME_FORMAT",
|
||||
)
|
||||
if item.program_times.all()
|
||||
else None
|
||||
),
|
||||
),
|
||||
FunctionalWalletTextPlaceholder(
|
||||
"program_end",
|
||||
GettextLocalizableString.gettext("Programm times: End"),
|
||||
{"item", "subevent_or_event"},
|
||||
lambda item, subevent_or_event: (
|
||||
LocalizableDatetime(
|
||||
max(pt.end for pt in item.program_times.all()).astimezone(
|
||||
subevent_or_event.timezone
|
||||
),
|
||||
"SHORT_DATETIME_FORMAT",
|
||||
)
|
||||
if item.program_times.all()
|
||||
else None
|
||||
),
|
||||
),
|
||||
FunctionalWalletTextPlaceholder(
|
||||
"organizer",
|
||||
GettextLocalizableString.gettext("Organizer"),
|
||||
{"organizer"},
|
||||
lambda organizer: organizer.name,
|
||||
),
|
||||
FunctionalWalletTextPlaceholder(
|
||||
"organizer_contact",
|
||||
GettextLocalizableString.gettext("Organizer Contact"),
|
||||
{"event"},
|
||||
lambda event: event.settings.contact_mail,
|
||||
"contact@example.com",
|
||||
),
|
||||
FunctionalWalletTextPlaceholder(
|
||||
"order_code",
|
||||
GettextLocalizableString.gettext("Order Code"),
|
||||
{"order"},
|
||||
lambda order: order.code,
|
||||
),
|
||||
FunctionalWalletTextPlaceholder(
|
||||
"purchase_date",
|
||||
GettextLocalizableString.gettext("Purchase Date"),
|
||||
{"order", "subevent_or_event"},
|
||||
lambda order, subevent_or_event: LocalizableDatetime(
|
||||
order.datetime.astimezone(subevent_or_event.timezone),
|
||||
"SHORT_DATETIME_FORMAT",
|
||||
),
|
||||
),
|
||||
FunctionalWalletTextPlaceholder(
|
||||
"website",
|
||||
GettextLocalizableString.gettext("Website"),
|
||||
{"order_position", "order"},
|
||||
website,
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,37 @@
|
||||
from typing import Iterable
|
||||
|
||||
from pretix.base.models import Event
|
||||
|
||||
from .base import (
|
||||
PassStyle, PassStyleRegistry, WalletPlatform, WalletPlatformRegistry,
|
||||
)
|
||||
|
||||
wallet_platform_registry = WalletPlatformRegistry()
|
||||
pass_style_registry = PassStyleRegistry()
|
||||
|
||||
|
||||
def get_available_platforms(
|
||||
event: Event, show_disabled: bool = False
|
||||
) -> Iterable[WalletPlatform]:
|
||||
for p, _ in wallet_platform_registry.filter(active_in=event):
|
||||
platform = p(event)
|
||||
if platform.is_available() and (show_disabled or platform.is_enabled()):
|
||||
yield platform
|
||||
|
||||
|
||||
def get_platform(
|
||||
event: Event, platform: str, show_disabled: bool
|
||||
) -> WalletPlatform | None:
|
||||
for p in get_available_platforms(event, show_disabled):
|
||||
if p.identifier == platform:
|
||||
return p
|
||||
|
||||
|
||||
__all__ = [
|
||||
"get_available_platforms",
|
||||
"get_platform",
|
||||
"pass_style_registry",
|
||||
"PassStyle",
|
||||
"wallet_platform_registry",
|
||||
"WalletPlatform",
|
||||
]
|
||||
@@ -0,0 +1,724 @@
|
||||
import enum
|
||||
from functools import cached_property
|
||||
from typing import Any, Iterable, TypedDict
|
||||
|
||||
import jsonschema
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.core.files import File
|
||||
from django.utils.functional import classproperty
|
||||
from django.utils.html import format_html
|
||||
from django.utils.translation import gettext as _
|
||||
from i18nfield.strings import LazyI18nString
|
||||
|
||||
from pretix.api.helpers import handle_file_upload
|
||||
from pretix.base.i18n import MaybeTranslatedString
|
||||
from pretix.base.models import OrderPosition
|
||||
from pretix.base.models.orders import Order
|
||||
from pretix.base.models.wallet import WalletLayout, WalletPlatformLayout
|
||||
from pretix.base.settings import SettingsSandbox
|
||||
from pretix.base.signals import PluginAwareRegistry, is_app_active
|
||||
from pretix.base.wallet.placeholders import (
|
||||
WalletPlaceholderRenderer, get_available_context,
|
||||
get_wallet_placeholder_renderer, get_wallet_placeholders,
|
||||
)
|
||||
from pretix.helpers.i18n import localizable_to_dict
|
||||
|
||||
from .settings import SettingsField, SettingsFile
|
||||
|
||||
|
||||
class WalletPlatform:
|
||||
identifier: str
|
||||
name: str
|
||||
|
||||
# TODO: register urls here?
|
||||
def __init__(self, event):
|
||||
self.event = event
|
||||
self.wallet_settings = SettingsSandbox("ticketoutput", "wallet", event)
|
||||
|
||||
def is_enabled(self):
|
||||
if not self.wallet_settings.get("_enabled", as_type=bool):
|
||||
return False
|
||||
return True
|
||||
|
||||
def is_available(self) -> bool:
|
||||
return True
|
||||
|
||||
def is_available_for_position(self, op: OrderPosition):
|
||||
return op.generate_ticket and bool(self.get_layout(op))
|
||||
|
||||
@classmethod
|
||||
def get_global_settings(cls, **kwargs):
|
||||
"""
|
||||
Return a list of fields for the global settings form, as a dict of (setting name, form field).
|
||||
"""
|
||||
return {}
|
||||
|
||||
@classproperty
|
||||
def default_style(cls) -> None | str: # noqa: N805
|
||||
return None
|
||||
|
||||
def render_download_button(self) -> tuple[dict[str, str] | None, str]:
|
||||
"""
|
||||
Render the download button that should be shown.
|
||||
|
||||
returns: A tuple of (attr, content).
|
||||
attr: the html attributes that should be added to the button element as a dict[str, str] or None
|
||||
content: the content of the button
|
||||
"""
|
||||
return None, format_html(
|
||||
'<span class="fa fa-download"></span> {}',
|
||||
_("Add to {wallet}").format(wallet=self.name),
|
||||
)
|
||||
|
||||
def get_layout(self, op) -> WalletPlatformLayout | None:
|
||||
if hasattr(op.item, "walletlayout"):
|
||||
wallet_layout = op.item.walletlayout.layout
|
||||
else:
|
||||
try:
|
||||
wallet_layout = op.event.wallet_layouts.get(default=True)
|
||||
except WalletLayout.DoesNotExist:
|
||||
return None
|
||||
return wallet_layout.platform_layouts.filter(platform=self.identifier).first()
|
||||
|
||||
def generate(self, position) -> str:
|
||||
"""
|
||||
This method should generate the wallet pass and return a url the user should be sent
|
||||
to to retrieve that pass (e.g. via download or by redirecting to the wallet provider)
|
||||
|
||||
.. note:: You should cache the generated files where possible and only regenerate
|
||||
if the pass content has changed.
|
||||
"""
|
||||
op_layout = self.get_layout(position)
|
||||
if not op_layout:
|
||||
raise ValueError(_("No layout defined for order position"))
|
||||
layout = op_layout.pass_layout
|
||||
return layout.generate(position)
|
||||
|
||||
def generate_order(self, order: Order) -> str:
|
||||
"""
|
||||
This method should generate the wallet passes for all positions in `order` and return
|
||||
a url the user should be sent to to retrieve them (e.g. via download or by redirecting
|
||||
to the wallet provider)
|
||||
|
||||
.. note:: You should cache the generated files where possible and only regenerate
|
||||
if the pass contents have changed.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def generate_preview(
|
||||
self, position: OrderPosition, layout: "PassStyle"
|
||||
) -> str | tuple[str, str, bytes]:
|
||||
"""
|
||||
This method should generate the wallet pass for `position` and either return a string containing
|
||||
a url the user should be sent to or a a tuple of an extension (str), a mimetype (str) and the data
|
||||
(bytes) for a file that should be downloaded to the user.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
class LayoutContext(TypedDict):
|
||||
placeholders: dict[str, dict]
|
||||
placeholder_renderer: WalletPlaceholderRenderer
|
||||
|
||||
|
||||
class FieldGroupType(enum.Enum):
|
||||
PLACEHOLDER = "placeholder"
|
||||
PREDEFINED = "predefined"
|
||||
|
||||
|
||||
class FieldGroupDisplay(enum.Enum):
|
||||
PLAIN = "plain"
|
||||
WITH_LABEL = "with_label"
|
||||
|
||||
|
||||
class FieldGroup:
|
||||
type: FieldGroupType
|
||||
identifier: str
|
||||
name: str
|
||||
description: str
|
||||
required: bool = False
|
||||
|
||||
def __init__(self, identifier: str, name: str, description=None, required=False):
|
||||
self.identifier = identifier
|
||||
self.name = name
|
||||
self.required = required
|
||||
self.description = description or ""
|
||||
|
||||
def layout_schema(
|
||||
self,
|
||||
remaining_fields: list["FieldGroup"],
|
||||
context: LayoutContext,
|
||||
) -> dict:
|
||||
raise NotImplementedError()
|
||||
|
||||
def asdict(
|
||||
self,
|
||||
locales: list[str],
|
||||
context: LayoutContext,
|
||||
remaining_fields: list["FieldGroup"],
|
||||
):
|
||||
return {
|
||||
"type": self.type.value,
|
||||
"identifier": self.identifier,
|
||||
"name": self.name,
|
||||
"description": self.description,
|
||||
"required": self.required,
|
||||
}
|
||||
|
||||
def default(self, locales: list[str]) -> dict[str, Any]:
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
class FieldContentType(enum.Enum):
|
||||
IMAGE = "image"
|
||||
TEXT = "text"
|
||||
|
||||
|
||||
class FieldEntryType(enum.Enum):
|
||||
CUSTOM = "custom"
|
||||
PLACEHOLDER = "placeholder"
|
||||
|
||||
|
||||
class FieldEntry[T]:
|
||||
type: FieldEntryType
|
||||
label: MaybeTranslatedString | None
|
||||
content: T
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
type: FieldEntryType,
|
||||
content: T,
|
||||
label: MaybeTranslatedString | None = None,
|
||||
):
|
||||
self.type = type
|
||||
self.label = label
|
||||
self.content = content
|
||||
|
||||
def asdict(self, locales: list[str]) -> dict:
|
||||
return {
|
||||
"type": self.type.value,
|
||||
"content": self.content,
|
||||
"label": (
|
||||
localizable_to_dict(self.label, locales)
|
||||
if self.label is not None
|
||||
else None
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
class PlaceholderFieldEntry(FieldEntry[str]):
|
||||
type = FieldEntryType.PLACEHOLDER
|
||||
content: str
|
||||
|
||||
def __init__(self, content: str, label: MaybeTranslatedString | None = None):
|
||||
self.label = label
|
||||
self.content = content
|
||||
|
||||
|
||||
class CustomFieldEntry(FieldEntry[MaybeTranslatedString]):
|
||||
type: FieldEntryType
|
||||
content: MaybeTranslatedString
|
||||
|
||||
def asdict(self, locales: list[str]) -> dict:
|
||||
return {
|
||||
"type": self.type.value,
|
||||
"content": localizable_to_dict(self.content, locales),
|
||||
"label": localizable_to_dict(self.label, locales) if self.label else None,
|
||||
}
|
||||
|
||||
|
||||
class PredefinedFieldGroup(FieldGroup):
|
||||
type = FieldGroupType.PREDEFINED
|
||||
default_active: bool
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
identifier: str,
|
||||
name: str,
|
||||
description=None,
|
||||
required=False,
|
||||
default_active=True,
|
||||
):
|
||||
self.identifier = identifier
|
||||
self.name = name
|
||||
self.required = required
|
||||
self.description = description or ""
|
||||
self.default_active = default_active
|
||||
|
||||
def layout_schema(
|
||||
self,
|
||||
remaining_fields: list["FieldGroup"],
|
||||
context: LayoutContext,
|
||||
):
|
||||
return {"type": "object", "properties": {"active": {"type": "boolean"}}}
|
||||
|
||||
def asdict(self, *args, **kwargs):
|
||||
return {
|
||||
**super().asdict(*args, **kwargs),
|
||||
"default_active": self.default_active,
|
||||
}
|
||||
|
||||
def default(self, locales):
|
||||
return {"active": self.default_active}
|
||||
|
||||
|
||||
class PlaceholderFieldGroup(FieldGroup):
|
||||
type = FieldGroupType.PLACEHOLDER
|
||||
content_type: FieldContentType
|
||||
default_entries: list[FieldEntry]
|
||||
display: FieldGroupDisplay
|
||||
min_entries: int | None
|
||||
max_entries: int | None
|
||||
context_args: set[
|
||||
str
|
||||
] # what context arguments are available when rendering this fieldgroup
|
||||
can_overflow: bool
|
||||
default_overflow: str | None
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
identifier: str,
|
||||
name: str,
|
||||
content_type: FieldContentType,
|
||||
description: str = "",
|
||||
required=False,
|
||||
default_entries=None,
|
||||
min_entries=None,
|
||||
max_entries=None,
|
||||
display=FieldGroupDisplay.WITH_LABEL,
|
||||
context_args: set[str] | None = None,
|
||||
can_overflow: bool = True,
|
||||
default_overflow: str | None = None,
|
||||
):
|
||||
super().__init__(identifier, name, description, required)
|
||||
self.content_type = content_type
|
||||
self.default_entries = default_entries or []
|
||||
self.min_entries = min_entries
|
||||
self.max_entries = max_entries
|
||||
self.display = display
|
||||
self.context_args = context_args or set()
|
||||
self.can_overflow = can_overflow
|
||||
self.default_overflow = default_overflow
|
||||
|
||||
if self.required and (self.min_entries is None or self.min_entries < 1):
|
||||
self.min_entries = 1
|
||||
|
||||
def asdict(
|
||||
self,
|
||||
locales: list[str],
|
||||
context: LayoutContext,
|
||||
remaining_fields: list[FieldGroup],
|
||||
):
|
||||
return {
|
||||
**super().asdict(locales, context, remaining_fields),
|
||||
"content_type": self.content_type.value,
|
||||
"default_entries": [x.asdict(locales) for x in self.default_entries],
|
||||
"display": self.display.value,
|
||||
"min_entries": self.min_entries,
|
||||
"max_entries": self.max_entries,
|
||||
"context_args": list(
|
||||
get_available_context(
|
||||
self.context_args, context["placeholder_renderer"].transformations
|
||||
)
|
||||
),
|
||||
"overflows": self.overflows(
|
||||
remaining_fields, context, self.available_placeholders(context)
|
||||
),
|
||||
"default_overflow": self.default_overflow,
|
||||
}
|
||||
|
||||
def default(self, locales):
|
||||
return {"entries": [x.asdict(locales) for x in self.default_entries]}
|
||||
|
||||
def available_placeholders(self, context):
|
||||
content_type_placeholders = (
|
||||
context["placeholders"].get(self.content_type.value, {}).values()
|
||||
)
|
||||
renderer = context["placeholder_renderer"]
|
||||
available_placeholders = [
|
||||
x.identifier
|
||||
for x in content_type_placeholders
|
||||
if renderer.is_available(x, self.context_args)
|
||||
]
|
||||
return available_placeholders
|
||||
|
||||
def overflows(self, remaining_fields, context, available_placeholders):
|
||||
if self.can_overflow:
|
||||
return [
|
||||
f.identifier
|
||||
for f in remaining_fields
|
||||
if isinstance(f, PlaceholderFieldGroup)
|
||||
and f.content_type == self.content_type
|
||||
and f.display == self.display
|
||||
and set(available_placeholders)
|
||||
<= set(f.available_placeholders(context))
|
||||
]
|
||||
else:
|
||||
return []
|
||||
|
||||
def layout_schema(
|
||||
self,
|
||||
remaining_fields: list["FieldGroup"],
|
||||
context: LayoutContext,
|
||||
):
|
||||
available_placeholders = self.available_placeholders(context)
|
||||
|
||||
return {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"entries": self.entries_schema(placeholders=available_placeholders),
|
||||
"overflow": {
|
||||
"anyOf": [
|
||||
{"type": "null"},
|
||||
{
|
||||
"type": "string",
|
||||
"enum": self.overflows(
|
||||
remaining_fields, context, available_placeholders
|
||||
),
|
||||
},
|
||||
]
|
||||
},
|
||||
},
|
||||
"required": ["entries"],
|
||||
}
|
||||
|
||||
def entries_schema(self, placeholders: list[str]):
|
||||
baseprops = {}
|
||||
if self.display == FieldGroupDisplay.WITH_LABEL:
|
||||
baseprops["label"] = {"$ref": "#/$defs/I18nString"}
|
||||
|
||||
schema = {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"anyOf": [
|
||||
{
|
||||
"properties": {
|
||||
**baseprops,
|
||||
"type": {"const": "placeholder"},
|
||||
"content": {"enum": placeholders},
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
**baseprops,
|
||||
"type": {"const": "custom"},
|
||||
"content": {"$ref": "#/$defs/I18nString"},
|
||||
}
|
||||
},
|
||||
],
|
||||
"required": ["type", "content"],
|
||||
},
|
||||
}
|
||||
if self.display == FieldGroupDisplay.WITH_LABEL:
|
||||
schema["items"]["required"].append("label")
|
||||
if self.min_entries is not None:
|
||||
schema["minItems"] = self.min_entries
|
||||
# max_entries is not enforced here, as the layout can have more fields than that (null-fields are removed, rest is overspilled)
|
||||
return schema
|
||||
|
||||
|
||||
class TextFieldGroup(PlaceholderFieldGroup):
|
||||
content_type = FieldContentType.TEXT
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(content_type=self.content_type, **kwargs)
|
||||
|
||||
|
||||
class ImageFieldGroup(PlaceholderFieldGroup):
|
||||
content_type = FieldContentType.IMAGE
|
||||
display = FieldGroupDisplay.PLAIN
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(content_type=self.content_type, display=self.display, **kwargs)
|
||||
|
||||
|
||||
class PassStyle:
|
||||
platform: type[WalletPlatform]
|
||||
identifier: str # unique within platform
|
||||
name: str
|
||||
|
||||
def __init__(
|
||||
self, event, layout=None, file_settings: dict[str, File] | None = None
|
||||
):
|
||||
self.event = event
|
||||
self.layout = layout
|
||||
self.file_settings = file_settings or {}
|
||||
self.placeholders = get_wallet_placeholders(self.event)
|
||||
|
||||
@property
|
||||
def fieldgroups(self) -> list[FieldGroup]:
|
||||
# order here limits in what order users can configure field "overspilling" (if too many fields are defined, where should the rest go)
|
||||
# -> can only go down in the list
|
||||
# we evaluate the fields in this order, so they overspill in this order as well
|
||||
return []
|
||||
|
||||
@property
|
||||
def settings(self) -> list[SettingsField]:
|
||||
return []
|
||||
|
||||
@cached_property
|
||||
def _settings_dict(self):
|
||||
return {x.identifier: x for x in self.settings}
|
||||
|
||||
@property
|
||||
def preview_renderer(self) -> str | None:
|
||||
return None
|
||||
|
||||
@property
|
||||
def preview_data(self) -> dict:
|
||||
return {}
|
||||
|
||||
@property
|
||||
def default_layout(self) -> dict:
|
||||
return {
|
||||
"fieldgroups": {
|
||||
fieldgroup.identifier: fieldgroup.default(self.event.settings.locales)
|
||||
for fieldgroup in self.fieldgroups
|
||||
},
|
||||
}
|
||||
|
||||
def get_cleaned_setting(
|
||||
self, setting_identifier: str
|
||||
) -> SettingsFile | str | float | bool | None:
|
||||
if not self.layout:
|
||||
raise ValueError("`layout` needs to be set")
|
||||
|
||||
setting = self._settings_dict.get(setting_identifier)
|
||||
|
||||
if not setting:
|
||||
return None
|
||||
|
||||
if setting.type == "image":
|
||||
val = self.file_settings.get(setting.identifier)
|
||||
else:
|
||||
val = self.layout.get("settings", {}).get(
|
||||
setting.identifier, setting.default
|
||||
)
|
||||
|
||||
return setting.clean(val)
|
||||
|
||||
def asdict(self):
|
||||
context = LayoutContext(
|
||||
placeholders=self.placeholders,
|
||||
placeholder_renderer=get_wallet_placeholder_renderer(),
|
||||
)
|
||||
return {
|
||||
"identifier": self.identifier,
|
||||
"name": self.name,
|
||||
"fieldgroups": [
|
||||
x.asdict(
|
||||
self.event.settings.locales,
|
||||
context,
|
||||
remaining_fields=self.fieldgroups[i:],
|
||||
)
|
||||
for i, x in enumerate(self.fieldgroups, 1)
|
||||
],
|
||||
"preview_renderer": self.preview_renderer,
|
||||
"preview_data": self.preview_data,
|
||||
"settings": [x.asdict(self.event.settings.locales) for x in self.settings],
|
||||
}
|
||||
|
||||
def layout_schema(self):
|
||||
context = LayoutContext(
|
||||
placeholders=self.placeholders,
|
||||
placeholder_renderer=get_wallet_placeholder_renderer(),
|
||||
)
|
||||
schema = {
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
# TODO: $id
|
||||
"title": self.name,
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"fieldgroups": {
|
||||
"description": "Layout Field Groups",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
group.identifier: group.layout_schema(
|
||||
context=context, remaining_fields=self.fieldgroups[i:]
|
||||
)
|
||||
for (i, group) in enumerate(self.fieldgroups, 1)
|
||||
},
|
||||
"required": [
|
||||
group.identifier for group in self.fieldgroups if group.required
|
||||
],
|
||||
},
|
||||
"settings": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
setting.identifier: setting.layout_schema()
|
||||
for setting in self.settings
|
||||
if setting.layout_schema()
|
||||
},
|
||||
"required": [
|
||||
setting.identifier
|
||||
for setting in self.settings
|
||||
if setting.required and setting.layout_schema()
|
||||
],
|
||||
},
|
||||
},
|
||||
"$defs": {
|
||||
"I18nString": {
|
||||
"oneOf": [
|
||||
{"type": "string"},
|
||||
{"type": "object", "additionalProperties": {"type": "string"}},
|
||||
]
|
||||
}
|
||||
},
|
||||
}
|
||||
if any(group.required for group in self.fieldgroups):
|
||||
schema.setdefault("required", [])
|
||||
schema["required"].append("fieldgroups")
|
||||
if any(
|
||||
setting.required and setting.type == "text" for setting in self.settings
|
||||
):
|
||||
schema.setdefault("required", [])
|
||||
schema["required"].append("settings")
|
||||
|
||||
return schema
|
||||
|
||||
def render_placeholder(self, context, content_type, content):
|
||||
placeholder = self.placeholders.get(content_type, {}).get(content)
|
||||
if placeholder:
|
||||
placeholder_value = context.render_placeholder(placeholder)
|
||||
if placeholder_value:
|
||||
return placeholder.label, placeholder_value
|
||||
|
||||
return None, None
|
||||
|
||||
def validate(self):
|
||||
schema = self.layout_schema()
|
||||
try:
|
||||
jsonschema.validate(self.layout, schema)
|
||||
except jsonschema.ValidationError as e:
|
||||
raise ValidationError("Invalid layout: {}".format(str(e)))
|
||||
|
||||
def extract_file_settings(self, request, file_settings):
|
||||
res = {}
|
||||
for setting in self.settings:
|
||||
if setting.type == "image":
|
||||
if file_settings.get(setting.identifier) == "file:keep":
|
||||
res[setting.identifier] = "keep"
|
||||
elif data := file_settings.get(setting.identifier):
|
||||
res[setting.identifier] = handle_file_upload(
|
||||
data,
|
||||
request.user,
|
||||
getattr(request, "auth", None),
|
||||
{"image/png", "image/jpeg"},
|
||||
)
|
||||
|
||||
return res
|
||||
|
||||
def _render_placeholder_fieldgroup_entries(self, group, context):
|
||||
group_fields = []
|
||||
if group.identifier not in self.layout["fieldgroups"]:
|
||||
return group_fields
|
||||
|
||||
for field in self.layout["fieldgroups"][group.identifier]["entries"]:
|
||||
field_entry: dict[str, MaybeTranslatedString | None] = {}
|
||||
if group.display == FieldGroupDisplay.WITH_LABEL:
|
||||
field_entry["label"] = LazyI18nString(field["label"])
|
||||
if field["type"] == FieldEntryType.PLACEHOLDER.value:
|
||||
label, field_entry["value"] = self.render_placeholder(
|
||||
context, group.content_type.value, field["content"]
|
||||
)
|
||||
if (
|
||||
group.display == FieldGroupDisplay.WITH_LABEL
|
||||
and not str(field_entry["label"])
|
||||
and label
|
||||
):
|
||||
field_entry["label"] = label
|
||||
|
||||
elif field["type"] == FieldEntryType.CUSTOM.value:
|
||||
field_entry["value"] = LazyI18nString(field["content"])
|
||||
if "value" in field_entry and field_entry["value"]:
|
||||
group_fields.append(field_entry)
|
||||
|
||||
return group_fields
|
||||
|
||||
def get_pass_fields(self, op: OrderPosition):
|
||||
if not self.layout:
|
||||
raise ValueError("`layout` needs to be set")
|
||||
|
||||
context = get_wallet_placeholder_renderer(event=self.event, order_position=op)
|
||||
|
||||
fields = {}
|
||||
for group in self.fieldgroups:
|
||||
if not isinstance(group, PlaceholderFieldGroup):
|
||||
continue
|
||||
|
||||
fields.setdefault(group.identifier, [])
|
||||
fields[group.identifier] += self._render_placeholder_fieldgroup_entries(
|
||||
group, context
|
||||
)
|
||||
if group.min_entries and len(fields[group.identifier]) < group.min_entries:
|
||||
raise ValueError(
|
||||
f"Group {group.identifier} needs at least {group.min_entries} entries, but only {len(fields[group.identifier])} were provided"
|
||||
)
|
||||
|
||||
if (
|
||||
overflow_group := self.layout["fieldgroups"]
|
||||
.get(group.identifier, {})
|
||||
.get("overflow")
|
||||
):
|
||||
fields.setdefault(overflow_group, [])
|
||||
fields[overflow_group] += fields[group.identifier][group.max_entries:]
|
||||
fields[group.identifier] = fields[group.identifier][: group.max_entries]
|
||||
|
||||
return fields
|
||||
|
||||
def group_is_active(self, identifier: str):
|
||||
if not self.layout:
|
||||
raise ValueError("`layout` needs to be set")
|
||||
|
||||
return self.layout["fieldgroups"].get(identifier, {}).get("active", False)
|
||||
|
||||
def generate(self, op: OrderPosition):
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
class PluginAwareClassRegistry[T](PluginAwareRegistry):
|
||||
base_class: type[T]
|
||||
|
||||
def register(self, *objs):
|
||||
for obj in objs:
|
||||
if not issubclass(obj, self.base_class):
|
||||
raise TypeError(f"Entries must be derived from {self.base_class}")
|
||||
|
||||
return super().register(*objs)
|
||||
|
||||
def filter(
|
||||
self, active_in=None, **kwargs
|
||||
) -> Iterable[tuple[type[T], dict[str, Any]]]:
|
||||
result = super().filter(**kwargs)
|
||||
if active_in is not None:
|
||||
result = (
|
||||
(entry, meta)
|
||||
for entry, meta in result
|
||||
if is_app_active(active_in, meta["plugin"])
|
||||
)
|
||||
return result
|
||||
|
||||
def get(
|
||||
self, active_in=None, **kwargs
|
||||
) -> tuple[type[T], dict[str, Any]] | tuple[None, None]:
|
||||
return super().get(active_in=active_in, **kwargs)
|
||||
|
||||
|
||||
class WalletPlatformRegistry(PluginAwareClassRegistry[WalletPlatform]):
|
||||
base_class = WalletPlatform
|
||||
|
||||
def __init__(self):
|
||||
super().__init__({"identifier": lambda o: o.identifier})
|
||||
|
||||
|
||||
class PassStyleRegistry(PluginAwareClassRegistry[PassStyle]):
|
||||
base_class = PassStyle
|
||||
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
{
|
||||
"identifier": lambda o: (o.platform.identifier, o.identifier),
|
||||
"platform": lambda o: o.platform.identifier,
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,242 @@
|
||||
import tempfile
|
||||
from typing import Any, Callable, Literal, Protocol, runtime_checkable
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.staticfiles import finders
|
||||
from django.core.files import File
|
||||
from django.core.files.uploadedfile import SimpleUploadedFile
|
||||
from django.db.models.fields.files import FieldFile
|
||||
from django.forms import ValidationError
|
||||
from django.templatetags.static import static
|
||||
from django.utils.translation import gettext as _
|
||||
|
||||
SettingType = Literal["image", "text", "float", "color", "bool"]
|
||||
JsonSerializable = int | bool | float | str | None
|
||||
|
||||
|
||||
class SettingsField[T, I = T]:
|
||||
identifier: str
|
||||
label: str
|
||||
type: SettingType
|
||||
help_text: str | None
|
||||
required: bool
|
||||
default: Any | None
|
||||
|
||||
def asdict(self, locales: list[str]):
|
||||
return {
|
||||
"identifier": self.identifier,
|
||||
"label": self.label,
|
||||
"type": self.type,
|
||||
"help_text": self.help_text,
|
||||
"required": self.required,
|
||||
"default": self.get_default(),
|
||||
}
|
||||
|
||||
def layout_schema(self) -> dict[str, Any] | None:
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_default(self) -> JsonSerializable:
|
||||
if isinstance(self.default, JsonSerializable):
|
||||
return self.default
|
||||
elif self.default:
|
||||
raise NotImplementedError()
|
||||
|
||||
def clean(self, value: I | None) -> T | None:
|
||||
if value:
|
||||
return value
|
||||
|
||||
if self.default:
|
||||
return self.default
|
||||
|
||||
|
||||
class TextSettingsField(SettingsField[str]):
|
||||
def __init__(
|
||||
self,
|
||||
identifier: str,
|
||||
label: str,
|
||||
help_text: str | None = None,
|
||||
required: bool = False,
|
||||
default: str | None = None,
|
||||
):
|
||||
self.identifier = identifier
|
||||
self.label = label
|
||||
self.type = "text"
|
||||
self.help_text = help_text
|
||||
self.required = required
|
||||
self.default = default
|
||||
|
||||
def layout_schema(self) -> dict[str, Any] | None:
|
||||
schema = {"type": "string"}
|
||||
if not self.required:
|
||||
schema = {"oneOf": [schema, {"type": "null"}]}
|
||||
return schema
|
||||
|
||||
|
||||
class ColorSettingsField(SettingsField[str]):
|
||||
def __init__(
|
||||
self,
|
||||
identifier: str,
|
||||
label: str,
|
||||
help_text: str | None = None,
|
||||
required: bool = False,
|
||||
default: str | None = None,
|
||||
):
|
||||
self.identifier = identifier
|
||||
self.label = label
|
||||
self.type = "color"
|
||||
self.help_text = help_text
|
||||
self.required = required
|
||||
self.default = default
|
||||
|
||||
def layout_schema(self) -> dict[str, Any] | None:
|
||||
# TODO: validate that '#' + 6 hex chars
|
||||
schema = {"type": "string"}
|
||||
if not self.required:
|
||||
schema = {"oneOf": [schema, {"type": "null"}]}
|
||||
return schema
|
||||
|
||||
|
||||
class FloatSettingsField(SettingsField[float]):
|
||||
min: float | None
|
||||
max: float | None
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
identifier: str,
|
||||
label: str,
|
||||
help_text=None,
|
||||
required: bool = False,
|
||||
min: float | None = None,
|
||||
max: float | None = None,
|
||||
default: float | None = None,
|
||||
):
|
||||
self.type = "float"
|
||||
self.identifier = identifier
|
||||
self.label = label
|
||||
self.help_text = help_text
|
||||
self.required = required
|
||||
self.min = min
|
||||
self.max = max
|
||||
self.default = default
|
||||
|
||||
def layout_schema(self):
|
||||
schema: dict[str, Any] = {"type": "number"}
|
||||
if self.min is not None:
|
||||
schema["minimum"] = self.min
|
||||
if self.max is not None:
|
||||
schema["maximum"] = self.max
|
||||
if not self.required:
|
||||
schema = {"oneOf": [schema, {"type": "null"}]}
|
||||
return schema
|
||||
|
||||
def asdict(self, locales: list[str]):
|
||||
return super().asdict(locales) | {"min": self.min, "max": self.max}
|
||||
|
||||
|
||||
class BooleanSettingsField(SettingsField[bool]):
|
||||
def __init__(
|
||||
self,
|
||||
identifier: str,
|
||||
label: str,
|
||||
help_text: str | None = None,
|
||||
default: bool = False,
|
||||
):
|
||||
self.type = "bool"
|
||||
self.identifier = identifier
|
||||
self.label = label
|
||||
self.help_text = help_text
|
||||
self.required = False
|
||||
self.default = default
|
||||
|
||||
def layout_schema(self):
|
||||
return {"type": "boolean"}
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class UrlAndReadFile(Protocol):
|
||||
url: str
|
||||
open: Callable
|
||||
seek: Callable
|
||||
read: Callable
|
||||
|
||||
|
||||
class SettingsFile:
|
||||
url: str
|
||||
file: UrlAndReadFile
|
||||
|
||||
def __init__(self, url, file):
|
||||
self.url = url
|
||||
self.file = file
|
||||
|
||||
|
||||
class ImageSettingsField(SettingsField[SettingsFile, FieldFile]):
|
||||
default: str | UrlAndReadFile | None = None
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
identifier: str,
|
||||
label: str,
|
||||
help_text: str | None = None,
|
||||
default: str | UrlAndReadFile | None = None,
|
||||
):
|
||||
self.identifier = identifier
|
||||
self.label = label
|
||||
self.type = "image"
|
||||
self.help_text = help_text
|
||||
self.required = False
|
||||
|
||||
if isinstance(default, UrlAndReadFile):
|
||||
self.default = default
|
||||
elif isinstance(default, str):
|
||||
if not finders.find(default):
|
||||
raise ValueError(f"Unknown file: {default}")
|
||||
self.default = default
|
||||
elif default:
|
||||
raise ValueError("Unsupported `default`")
|
||||
|
||||
def get_default(self):
|
||||
if isinstance(self.default, str):
|
||||
return static(self.default)
|
||||
elif isinstance(self.default, File):
|
||||
return self.default.url
|
||||
|
||||
def layout_schema(self):
|
||||
return
|
||||
|
||||
def clean(self, value):
|
||||
if value:
|
||||
return SettingsFile(value.url, value)
|
||||
|
||||
if isinstance(self.default, UrlAndReadFile):
|
||||
return SettingsFile(self.default.url, self.default)
|
||||
|
||||
if isinstance(self.default, str):
|
||||
return SettingsFile(
|
||||
static(self.default), File(None, finders.find(self.default))
|
||||
)
|
||||
|
||||
|
||||
def convert_to_png(file: SettingsFile, max_size=None):
|
||||
# TODO: move validation to upload
|
||||
try:
|
||||
from PIL import Image, ImageOps
|
||||
except ImportError:
|
||||
return file
|
||||
|
||||
file.file.open("rb")
|
||||
file.file.seek(0)
|
||||
try:
|
||||
with (
|
||||
Image.open(file.file, formats=settings.PILLOW_FORMATS_IMAGE) as im,
|
||||
tempfile.NamedTemporaryFile("rb", suffix=".png") as tmpfile,
|
||||
):
|
||||
im = ImageOps.exif_transpose(im)
|
||||
if max_size:
|
||||
im.thumbnail(max_size, resample=Image.Resampling.BICUBIC)
|
||||
im.save(tmpfile.name)
|
||||
tmpfile.seek(0)
|
||||
return SimpleUploadedFile("picture.png", tmpfile.read(), "image/png")
|
||||
except IOError:
|
||||
raise ValidationError(
|
||||
_("The file you uploaded could not be converted to PNG format.")
|
||||
)
|
||||
@@ -0,0 +1,22 @@
|
||||
from pretix.base.models import Order, OrderPosition
|
||||
from pretix.base.services.tasks import ProfiledTask
|
||||
from pretix.base.wallet.platforms import get_platform
|
||||
from pretix.celery_app import app
|
||||
|
||||
|
||||
@app.task(base=ProfiledTask)
|
||||
def get_pass(model: str, pk: int, platform_identifier: str, show_disabled: bool):
|
||||
if model == "order":
|
||||
order = Order.objects.select_related("event").get(id=pk)
|
||||
platform = get_platform(order.event, platform_identifier, show_disabled)
|
||||
if not platform:
|
||||
return
|
||||
return platform.generate_order(order)
|
||||
elif model == "orderposition":
|
||||
position = OrderPosition.objects.select_related("order", "order__event").get(
|
||||
id=pk
|
||||
)
|
||||
platform = get_platform(position.order.event, platform_identifier, show_disabled)
|
||||
if not platform:
|
||||
return
|
||||
return platform.generate(position)
|
||||
@@ -64,6 +64,7 @@ from pretix.base.models import Event, Organizer, TaxRule, Team
|
||||
from pretix.base.models.event import EventFooterLink, EventMetaValue, SubEvent
|
||||
from pretix.base.models.organizer import TeamQuerySet
|
||||
from pretix.base.models.tax import TAX_CODE_LISTS, VAT_ID_COUNTRIES
|
||||
from pretix.base.models.wallet import WalletLayout, WalletLayoutItem
|
||||
from pretix.base.reldate import RelativeDateField, RelativeDateTimeField
|
||||
from pretix.base.services.placeholders import FormPlaceholderMixin
|
||||
from pretix.base.settings import (
|
||||
@@ -1005,7 +1006,7 @@ class TaxSettingsForm(EventSettingsValidationMixin, SettingsForm):
|
||||
class ProviderForm(SettingsForm):
|
||||
"""
|
||||
This is a SettingsForm, but if fields are set to required=True, validation
|
||||
errors are only raised if the payment method is enabled.
|
||||
errors are only raised if the provider is enabled.
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
@@ -1656,6 +1657,7 @@ class TicketSettingsForm(SettingsForm):
|
||||
'ticket_download_pending',
|
||||
'ticket_download_require_validated_email',
|
||||
'ticket_secret_length',
|
||||
'ticket_wallet_enabled',
|
||||
]
|
||||
ticket_secret_generator = forms.ChoiceField(
|
||||
label=_("Ticket code generator"),
|
||||
@@ -2121,3 +2123,46 @@ EventFooterLinkFormset = inlineformset_factory(
|
||||
formset=BaseEventFooterLinkFormSet,
|
||||
can_order=False, can_delete=True, extra=0
|
||||
)
|
||||
|
||||
|
||||
class WalletLayoutCreateForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = WalletLayout
|
||||
fields = ("name",)
|
||||
|
||||
def __init__(self, *args, event, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.event = event
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
self.instance.event = self.event
|
||||
return super().save(*args, **kwargs)
|
||||
|
||||
|
||||
class WalletLayoutItemForm(forms.ModelForm):
|
||||
is_layouts = True
|
||||
layout = forms.ModelChoiceField(
|
||||
queryset=WalletLayout.objects.none(),
|
||||
label=_("Wallet Layout"),
|
||||
empty_label=_("(Event default)"),
|
||||
required=False,
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = WalletLayoutItem
|
||||
fields = ("layout",)
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.event = kwargs.pop("event")
|
||||
super().__init__(*args, **kwargs)
|
||||
self.fields["layout"].queryset = self.event.wallet_layouts.all()
|
||||
|
||||
def save(self, commit=True):
|
||||
if self.has_changed():
|
||||
if self.cleaned_data["layout"] is None:
|
||||
if self.instance.pk:
|
||||
self.instance.delete()
|
||||
else:
|
||||
self.instance.layout = self.cleaned_data["layout"]
|
||||
super().save(commit=commit)
|
||||
return self.instance
|
||||
@@ -133,12 +133,10 @@ def get_all_payment_providers():
|
||||
if isinstance(prov, list):
|
||||
for p in prov:
|
||||
p = p(event)
|
||||
if not p.is_meta:
|
||||
choices.append((p.identifier, p.verbose_name))
|
||||
choices.append((p.identifier, p.verbose_name))
|
||||
else:
|
||||
prov = prov(event)
|
||||
if not prov.is_meta:
|
||||
choices.append((prov.identifier, prov.verbose_name))
|
||||
choices.append((prov.identifier, prov.verbose_name))
|
||||
PAYMENT_PROVIDERS = choices
|
||||
return choices
|
||||
|
||||
|
||||
@@ -1207,11 +1207,6 @@ class ItemAddOnForm(I18nModelForm):
|
||||
}
|
||||
)
|
||||
self.fields['addon_category'].widget.choices = self.fields['addon_category'].choices
|
||||
self.fields['max_count'] = forms.IntegerField(
|
||||
min_value=1,
|
||||
label=self.fields['max_count'].label,
|
||||
widget=forms.NumberInput(attrs={'placeholder': '1'}),
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = ItemAddOn
|
||||
@@ -1324,12 +1319,6 @@ class ItemBundleForm(I18nModelForm):
|
||||
self.fields['itemvar'].choices = choices
|
||||
change_decimal_field(self.fields['designated_price'], self.event.currency)
|
||||
|
||||
self.fields['count'] = forms.IntegerField(
|
||||
min_value=1,
|
||||
label=self.fields['count'].label,
|
||||
widget=forms.NumberInput(attrs={'placeholder': '1'}),
|
||||
)
|
||||
|
||||
def clean(self):
|
||||
d = super().clean()
|
||||
if not self.cleaned_data.get('designated_price'):
|
||||
|
||||
@@ -79,8 +79,8 @@ class WaitingListEntryEditForm(I18nModelForm):
|
||||
self.fields['name_parts'] = NamePartsFormField(
|
||||
max_length=255,
|
||||
required=self.event.settings.waiting_list_names_required,
|
||||
scheme=self.event.settings.name_scheme,
|
||||
titles=self.event.settings.name_scheme_titles,
|
||||
scheme=self.event.organizer.settings.name_scheme,
|
||||
titles=self.event.organizer.settings.name_scheme_titles,
|
||||
label=_('Name'),
|
||||
)
|
||||
else:
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -481,5 +481,15 @@
|
||||
<div class="steps">
|
||||
</div>
|
||||
{% enddialog %}
|
||||
{% trans "Confirmation required" as confirmation_title %}
|
||||
{% dialog "confirmationmodal" confirmation_title "" icon="shield" %}
|
||||
<div class="modal-card-confirm modal-card-confirm-spread">
|
||||
<button type="button" class="btn btn-default btn-lg" commandfor="confirmationmodal" command="close">{% trans "Cancel" %}</button>
|
||||
<button type="button" id="confirmationmodal-confirm"
|
||||
class="btn btn-primary btn-lg">
|
||||
{% trans "Confirm" %}
|
||||
</button>
|
||||
</div>
|
||||
{% enddialog %}
|
||||
</body>
|
||||
</html>
|
||||
@@ -48,7 +48,27 @@
|
||||
{% endwith %}
|
||||
</div>
|
||||
</div>
|
||||
{% empty %}
|
||||
{% endfor %}
|
||||
{% if show_wallet %}
|
||||
<div class="panel panel-default ticketoutput-panel">
|
||||
<div class="panel-heading">
|
||||
<h3 class="panel-title">
|
||||
{% translate "Wallet" as wallet_label %}
|
||||
{% bootstrap_field form.ticket_wallet_enabled layout="inline" label=wallet_label %}
|
||||
</h3>
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<p>
|
||||
<a class="btn btn-primary btn-lg" target="_blank"
|
||||
href="{% url "control:event.wallet.index" organizer=request.organizer.slug event=request.event.slug %}">
|
||||
<span class="fa fa-paint-brush"></span>
|
||||
{% trans "Edit layouts" %}
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% if not providers and not show_wallet %}
|
||||
<div class="alert alert-warning">
|
||||
{% url "control:event.settings.plugins" event=request.event.slug organizer=request.organizer.slug as plugin_settings_url %}
|
||||
{% blocktrans trimmed with plugin_settings_href='href="'|add:plugin_settings_url|add:'"'|safe %}
|
||||
@@ -56,7 +76,7 @@
|
||||
<a {{ plugin_settings_href }}>plugin settings</a> and activate one or more ticket output plugins.
|
||||
{% endblocktrans %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>{% trans "Download time" %}</legend>
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
{% load l10n %}
|
||||
{% load phone_format %}
|
||||
{% load getitem %}
|
||||
{% load dialog %}
|
||||
{% block title %}
|
||||
{% blocktrans trimmed with code=order.code %}
|
||||
Order details: {{ code }}
|
||||
@@ -573,16 +574,30 @@
|
||||
</button>
|
||||
</form>
|
||||
{% endfor %}
|
||||
{% for b in wallet_buttons|getitem:line %}
|
||||
<form action="{% url "control:event.order.wallet.get" code=order.code event=request.event.slug organizer=request.event.organizer.slug position=line.pk platform=b.identifier %}"
|
||||
method="post" data-asynctask data-asynctask-download
|
||||
class="form-inline helper-display-inline">
|
||||
{% csrf_token %}
|
||||
<button type="submit"
|
||||
class="btn btn-xs btn-default {{ b.attributes.class }}"
|
||||
{% include "pretixbase/fragments/attributes.html" with attributes=b.attributes %}>
|
||||
{{ b.content }}
|
||||
</button>
|
||||
</form>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
<button type="submit" data-toggle="qrcode" data-qrcode="{{ line.secret }}"
|
||||
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 %}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
{% extends "pretixcontrol/event/base.html" %}
|
||||
{% load i18n %}
|
||||
{% load money %}
|
||||
{% load bootstrap3 %}
|
||||
{% load vite %}
|
||||
{% load static %}
|
||||
{% load compress %}
|
||||
|
||||
|
||||
{% block title %}{% trans "Wallet layouts" %}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<h1>{% trans "New layout" %}</h1>
|
||||
<form action="" method="post" class="form-horizontal">
|
||||
{% csrf_token %}
|
||||
{% bootstrap_form form layout="control" %}
|
||||
<div class="form-group">
|
||||
<label class="col-md-3 control-label">
|
||||
{% trans "Ticket design" %}
|
||||
</label>
|
||||
<div class="col-md-9 form-control-static">
|
||||
<p>
|
||||
{% blocktrans trimmed %}
|
||||
You can modify the design after you saved this page.
|
||||
{% endblocktrans %}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group submit-group">
|
||||
<button type="submit" class="btn btn-primary btn-save">
|
||||
{% trans "Save" %}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,25 @@
|
||||
{% extends "pretixcontrol/event/base.html" %}
|
||||
{% load i18n %}
|
||||
{% load bootstrap3 %}
|
||||
{% block title %}{% trans "Wallet layout" %}{% endblock %}
|
||||
{% block content %}
|
||||
<h1>{% trans "Wallet layout" %}</h1>
|
||||
<form action="" method="post" class="form-horizontal">
|
||||
{% csrf_token %}
|
||||
{% if object.allow_delete %}
|
||||
<p>{% blocktrans with name=object.name %}Are you sure you want to delete <strong>"{{ name }}"</strong>?{% endblocktrans %}</p>
|
||||
{% else %}
|
||||
<p>{% blocktrans %}You cannot delete the default layout.{% endblocktrans %}</p>
|
||||
{% endif %}
|
||||
<div class="form-group submit-group">
|
||||
<a href="{% url "control:event.wallet.index" organizer=request.event.organizer.slug event=request.event.slug %}" class="btn btn-default btn-cancel">
|
||||
{% trans "Cancel" %}
|
||||
</a>
|
||||
{% if object.allow_delete %}
|
||||
<button type="submit" class="btn btn-danger btn-save">
|
||||
{% trans "Delete" %}
|
||||
</button>
|
||||
{% endif %}
|
||||
</div>
|
||||
</form>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,24 @@
|
||||
{% extends "pretixcontrol/event/base.html" %}
|
||||
{% load i18n %}
|
||||
{% load money %}
|
||||
{% load bootstrap3 %}
|
||||
{% load vite %}
|
||||
{% load static %}
|
||||
{% load compress %}
|
||||
|
||||
|
||||
{% block title %}{% trans "Wallet layouts" %}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<h1>{% trans "Edit layout" %}</h1>
|
||||
{{ platforms|json_script:"platforms" }}
|
||||
{{ placeholders|json_script:"placeholders" }}
|
||||
{{ locales|json_script:"locales" }}
|
||||
<div id="editor" data-layout-id="{{ object.pk }}"
|
||||
data-base-url="{% url 'api-v1:walletlayout-list' organizer=request.organizer.slug event=request.event.slug %}"
|
||||
data-preview-url="{% url 'control:event.wallet.preview' organizer=request.organizer.slug event=request.event.slug %}"></div>
|
||||
{% vite_hmr %}
|
||||
{% vite_asset "src/pretix/static/pretixcontrol/wallet/main.ts" %}
|
||||
|
||||
{% csrf_token %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,77 @@
|
||||
{% extends "pretixcontrol/event/base.html" %}
|
||||
{% load i18n %}
|
||||
{% load money %}
|
||||
{% block title %}{% trans "Wallet layouts" %}{% endblock %}
|
||||
{% block content %}
|
||||
<h1>{% trans "Wallet layouts" %}</h1>
|
||||
{% if object_list|length == 0 %}
|
||||
<div class="empty-collection">
|
||||
<p>
|
||||
{% blocktrans trimmed %}
|
||||
You haven't created any layouts yet.
|
||||
{% endblocktrans %}
|
||||
</p>
|
||||
|
||||
{% if "event.settings.general:write" in request.eventpermset %}
|
||||
<a href="{% url "control:event.wallet.add" organizer=request.event.organizer.slug event=request.event.slug %}"
|
||||
class="btn btn-primary btn-lg"><i class="fa fa-plus"></i> {% trans "Create a new layout" %}
|
||||
</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="table-responsive">
|
||||
<table class="table table-hover table-quotas">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>{% trans "Name" %}</th>
|
||||
<th>{% trans "Default" %}</th>
|
||||
<th class="action-col-2"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for l in object_list %}
|
||||
<tr>
|
||||
<td>
|
||||
{% if "can_change_event_settings" in request.eventpermset %}
|
||||
<strong><a href="{% url "control:event.wallet.edit" organizer=request.event.organizer.slug event=request.event.slug layout=l.id %}">
|
||||
{{ l.name }}
|
||||
</a></strong>
|
||||
{% else %}
|
||||
<strong>{{ l.name }}</strong>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td>
|
||||
{% if l.default %}
|
||||
<span class="text-success">
|
||||
<span class="fa fa-check"></span>
|
||||
{% trans "Default" %}
|
||||
</span>
|
||||
{% elif "can_change_event_settings" in request.eventpermset %}
|
||||
<form class="form-inline" method="post"
|
||||
action="{% url "control:event.wallet.default" organizer=request.event.organizer.slug event=request.event.slug layout=l.id %}">
|
||||
{% csrf_token %}
|
||||
<button class="btn btn-default btn-sm">
|
||||
{% trans "Make default" %}
|
||||
</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td class="text-right flip">
|
||||
{% if "can_change_event_settings" in request.eventpermset %}
|
||||
<a href="{% url "control:event.wallet.edit" organizer=request.event.organizer.slug event=request.event.slug layout=l.id %}" class="btn btn-default btn-sm"><i class="fa fa-edit"></i></a>
|
||||
<a href="{% url "control:event.wallet.add" organizer=request.event.organizer.slug event=request.event.slug %}?copy_from={{ l.id }}"
|
||||
class="btn btn-default btn-sm" title="{% trans "Clone" %}" data-toggle="tooltip"><i class="fa fa-copy"></i></a>
|
||||
{% if l.allow_delete %}
|
||||
<a href="{% url "control:event.wallet.delete" organizer=request.event.organizer.slug event=request.event.slug layout=l.id %}" class="btn btn-danger btn-sm"><i class="fa fa-trash"></i></a>
|
||||
{% else %}
|
||||
<button class="btn btn-danger btn-sm" disabled><i class="fa fa-trash"></i></button>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,8 @@
|
||||
{% load i18n %}
|
||||
<p>
|
||||
<a class="btn btn-primary btn-lg" target="_blank"
|
||||
href="{% url "control:event.wallet.index" organizer=request.organizer.slug event=request.event.slug %}">
|
||||
<span class="fa fa-paint-brush"></span>
|
||||
{% trans "Edit layouts" %}
|
||||
</a>
|
||||
</p>
|
||||
@@ -43,6 +43,16 @@ from pretix.control.views import (
|
||||
waitinglist,
|
||||
)
|
||||
|
||||
from pretix.control.views.wallet import (
|
||||
LayoutCreateView,
|
||||
LayoutDelete,
|
||||
LayoutEditorView,
|
||||
LayoutListView,
|
||||
LayoutPreviewView,
|
||||
LayoutSetDefault,
|
||||
WalletGetView,
|
||||
)
|
||||
|
||||
urlpatterns = [
|
||||
re_path(r'^logout$', auth.logout, name='auth.logout'),
|
||||
re_path(r'^login$', auth.login, name='auth.login'),
|
||||
@@ -503,6 +513,41 @@ urlpatterns = [
|
||||
re_path(r'^checkinlists/(?P<list>\d+)/delete$', checkin.CheckinListDelete.as_view(),
|
||||
name='event.orders.checkinlists.delete'),
|
||||
re_path(r'^datasync/failedjobs/$', datasync.EventFailedSyncJobsView.as_view(), name='event.datasync.failedjobs'),
|
||||
re_path(
|
||||
r'^wallet/$',
|
||||
LayoutListView.as_view(),
|
||||
name='event.wallet.index',
|
||||
),
|
||||
re_path(
|
||||
r'^wallet/add/$',
|
||||
LayoutCreateView.as_view(),
|
||||
name='event.wallet.add',
|
||||
),
|
||||
re_path(
|
||||
r'^wallet/edit/(?P<layout>[^/]+)/$',
|
||||
LayoutEditorView.as_view(),
|
||||
name='event.wallet.edit',
|
||||
),
|
||||
re_path(
|
||||
r'^wallet/preview/$',
|
||||
LayoutPreviewView.as_view(),
|
||||
name='event.wallet.preview',
|
||||
),
|
||||
re_path(
|
||||
r'^wallet/default/(?P<layout>[^/]+)/$',
|
||||
LayoutSetDefault.as_view(),
|
||||
name='event.wallet.default',
|
||||
),
|
||||
re_path(
|
||||
r'^wallet/delete/(?P<layout>[^/]+)/$',
|
||||
LayoutDelete.as_view(),
|
||||
name='event.wallet.delete',
|
||||
),
|
||||
re_path(
|
||||
r'^orders/(?P<code>[0-9A-Z]+)/wallet/(?P<position>\d+)/(?P<platform>[^/]+)/$',
|
||||
WalletGetView.as_view(),
|
||||
name='event.order.wallet.get',
|
||||
),
|
||||
])),
|
||||
re_path(r'^event/(?P<organizer>[^/]+)/$', RedirectView.as_view(pattern_name='control:organizer'), name='event.organizerredirect'),
|
||||
]
|
||||
@@ -84,6 +84,7 @@ from pretix.base.services import tickets
|
||||
from pretix.base.services.invoices import build_preview_invoice_pdf
|
||||
from pretix.base.signals import get_defining_app, register_ticket_outputs
|
||||
from pretix.base.templatetags.rich_text import markdown_compile_email
|
||||
from pretix.base.wallet.platforms import wallet_platform_registry
|
||||
from pretix.control.forms.event import (
|
||||
CancelSettingsForm, CommentForm, ConfirmTextFormset, EventDeleteForm,
|
||||
EventFooterLinkFormset, EventMetaValueForm, EventSettingsForm,
|
||||
@@ -1012,6 +1013,7 @@ class TicketSettings(EventSettingsViewMixin, EventPermissionRequiredMixin, FormV
|
||||
def get_context_data(self, *args, **kwargs) -> dict:
|
||||
context = super().get_context_data(*args, **kwargs)
|
||||
context['providers'] = self.provider_forms
|
||||
context['show_wallet'] = any(wallet_platform_registry.filter(active_in=self.request.event))
|
||||
|
||||
context['any_enabled'] = False
|
||||
responses = register_ticket_outputs.send(self.request.event)
|
||||
@@ -1085,6 +1087,11 @@ class TicketSettings(EventSettingsViewMixin, EventPermissionRequiredMixin, FormV
|
||||
responses = register_ticket_outputs.send(self.request.event)
|
||||
for receiver, response in responses:
|
||||
provider = response(self.request.event)
|
||||
provider_settings_fields = provider.settings_form_fields
|
||||
provider_settings_content = provider.settings_content_render(self.request)
|
||||
if not provider_settings_fields and not provider_settings_content:
|
||||
continue
|
||||
|
||||
provider.form = ProviderForm(
|
||||
obj=self.request.event,
|
||||
settingspref='ticketoutput_%s_' % provider.identifier,
|
||||
@@ -1094,17 +1101,17 @@ class TicketSettings(EventSettingsViewMixin, EventPermissionRequiredMixin, FormV
|
||||
provider.form.fields = OrderedDict(
|
||||
[
|
||||
('ticketoutput_%s_%s' % (provider.identifier, k), v)
|
||||
for k, v in provider.settings_form_fields.items()
|
||||
for k, v in provider_settings_fields.items()
|
||||
]
|
||||
)
|
||||
provider.settings_content = provider.settings_content_render(self.request)
|
||||
provider.settings_content = provider_settings_content
|
||||
provider.form.prepare_fields()
|
||||
|
||||
provider.evaluated_preview_allowed = True
|
||||
if not provider.preview_allowed:
|
||||
provider.evaluated_preview_allowed = False
|
||||
else:
|
||||
for k, v in provider.settings_form_fields.items():
|
||||
for k, v in provider_settings_fields.items():
|
||||
if v.required and not self.request.event.settings.get('ticketoutput_%s_%s' % (provider.identifier, k)):
|
||||
provider.evaluated_preview_allowed = False
|
||||
break
|
||||
|
||||
@@ -1540,10 +1540,11 @@ class ItemUpdateGeneral(ItemDetailMixin, EventPermissionRequiredMixin, MetaDataE
|
||||
}
|
||||
for f in self.plugin_forms:
|
||||
change_data.update({
|
||||
k: (f.cleaned_data.get(k).name
|
||||
f"{f.prefix}-{k}": (
|
||||
f.cleaned_data.get(k).name
|
||||
if isinstance(f.cleaned_data.get(k), File)
|
||||
else f.cleaned_data.get(k))
|
||||
for k in f.changed_data
|
||||
else f.cleaned_data.get(k)
|
||||
) for k in f.changed_data
|
||||
})
|
||||
|
||||
meta_changed = {}
|
||||
|
||||
@@ -130,7 +130,6 @@ class OutgoingMailDetailView(OrganizerDetailViewMixin, OrganizerPermissionRequir
|
||||
|
||||
|
||||
class OutgoingMailBulkAction(OutgoingMailQueryMixin, OrganizerPermissionRequiredMixin, OrganizerDetailViewMixin, View):
|
||||
# Yes, read permission here includes retry and cancelling emails, this is intentional and documented
|
||||
permission = 'organizer.outgoingmails:read'
|
||||
|
||||
@transaction.atomic
|
||||
|
||||
@@ -43,6 +43,7 @@ from datetime import datetime, time, timedelta
|
||||
from decimal import Decimal, DecimalException
|
||||
from urllib.parse import quote, urlencode
|
||||
|
||||
from celery.result import AsyncResult
|
||||
from django import forms
|
||||
from django.conf import settings
|
||||
from django.contrib import messages
|
||||
@@ -109,7 +110,7 @@ from pretix.base.services.stats import order_overview
|
||||
from pretix.base.services.tax import (
|
||||
VATIDFinalError, VATIDTemporaryError, validate_vat_id,
|
||||
)
|
||||
from pretix.base.services.tickets import generate
|
||||
from pretix.base.services.tickets import generate, get_download_buttons, get_wallet_buttons
|
||||
from pretix.base.signals import order_modified, register_ticket_outputs
|
||||
from pretix.base.templatetags.money import money_filter
|
||||
from pretix.base.templatetags.rich_text import markdown_compile_email
|
||||
@@ -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
|
||||
@@ -544,7 +544,8 @@ class OrderDetail(OrderView):
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
ctx = super().get_context_data(**kwargs)
|
||||
ctx['items'] = self.get_items()
|
||||
items = self.get_items()
|
||||
ctx['items'] = items
|
||||
ctx['has_cancellation_fee'] = any(f.fee_type == OrderFee.FEE_TYPE_CANCELLATION for f in ctx['items']['fees'])
|
||||
ctx['event'] = self.request.event
|
||||
ctx['payments'] = self.order.payments.order_by('-created')
|
||||
@@ -566,7 +567,8 @@ class OrderDetail(OrderView):
|
||||
|
||||
pending_sum = self.order.pending_sum
|
||||
ctx['overpaid'] = pending_sum * -1
|
||||
ctx['download_buttons'] = self.download_buttons
|
||||
ctx['download_buttons'] = get_download_buttons(self.request.event, show_disabled=True)
|
||||
ctx['wallet_buttons'] = get_wallet_buttons(self.request.event, items['positions'], show_disabled=True)
|
||||
ctx['payment_refund_sum'] = self.order.payment_refund_sum
|
||||
ctx['pending_sum'] = pending_sum
|
||||
ctx['uncancelled_invoice'] = self.order.invoices.exclude(
|
||||
@@ -575,22 +577,6 @@ class OrderDetail(OrderView):
|
||||
|
||||
return ctx
|
||||
|
||||
@cached_property
|
||||
def download_buttons(self):
|
||||
buttons = []
|
||||
|
||||
responses = register_ticket_outputs.send(self.request.event)
|
||||
for receiver, response in responses:
|
||||
provider = response(self.request.event)
|
||||
buttons.append({
|
||||
'text': provider.download_button_text or 'Ticket',
|
||||
'icon': provider.download_button_icon or 'fa-download',
|
||||
'identifier': provider.identifier,
|
||||
'multi': provider.multi_download_enabled,
|
||||
'javascript_required': provider.javascript_required
|
||||
})
|
||||
return buttons
|
||||
|
||||
def get_items(self):
|
||||
queryset = self.object.all_positions
|
||||
|
||||
@@ -706,9 +692,9 @@ class OrderDownload(AsyncAction, OrderView):
|
||||
if 'position' in kwargs and not self.order_position.generate_ticket:
|
||||
return self.error(_('Ticket download is not enabled for this product.'))
|
||||
|
||||
ct = self.get_last_ct()
|
||||
if ct:
|
||||
if ct := self.get_last_ct():
|
||||
return self.success(ct)
|
||||
|
||||
return self.do('orderposition' if 'position' in kwargs else 'order',
|
||||
self.order_position.pk if 'position' in kwargs else self.order.pk,
|
||||
self.output.identifier)
|
||||
@@ -738,7 +724,7 @@ class OrderDownload(AsyncAction, OrderView):
|
||||
content_type=value.type
|
||||
)
|
||||
else:
|
||||
return redirect(self.get_self_url())
|
||||
return redirect(self.get_success_url(value))
|
||||
|
||||
def get_last_ct(self):
|
||||
ct = CachedTicket.objects.filter(
|
||||
@@ -2772,11 +2758,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 +2910,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 +3147,14 @@ class EventCancel(EventPermissionRequiredMixin, AsyncAction, FormView):
|
||||
|
||||
class EventCancelConfirm(EventPermissionRequiredMixin, AsyncAction, FormView):
|
||||
template_name = 'pretixcontrol/orders/cancel_confirm.html'
|
||||
permission = 'event:cancel'
|
||||
permission = 'event.orders:write'
|
||||
form_class = EventCancelConfirmForm
|
||||
task = cancel_event
|
||||
known_errortypes = ['OrderError']
|
||||
|
||||
@cached_property
|
||||
def dryrun_result(self):
|
||||
res = get_task_result(self.kwargs.get("task"), task_name=self.task)
|
||||
res = AsyncResult(self.kwargs.get("task"))
|
||||
if not res.ready():
|
||||
raise Http404()
|
||||
if not res.successful():
|
||||
|
||||
@@ -2056,11 +2056,7 @@ class ExportMixin:
|
||||
@cached_property
|
||||
def scheduled_copy_from(self):
|
||||
if "scheduled_copy_from" in self.request.GET:
|
||||
return get_object_or_404(
|
||||
self.get_scheduled_queryset(),
|
||||
pk=self.request.GET.get("scheduled_copy_from"),
|
||||
export_identifier=self.request.GET.get("identifier") or self.request.POST.get("exporter") or self.request.GET.get("exporter"),
|
||||
)
|
||||
return get_object_or_404(self.get_scheduled_queryset(), pk=self.request.GET.get("scheduled_copy_from"))
|
||||
|
||||
|
||||
class ExportDoView(OrganizerPermissionRequiredMixin, ExportMixin, AsyncAction, TemplateView):
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib import messages
|
||||
from django.core.exceptions import BadRequest
|
||||
from django.db import transaction
|
||||
from django.http import Http404, HttpResponse, HttpResponseRedirect
|
||||
from django.shortcuts import redirect
|
||||
from django.urls import reverse
|
||||
from django.utils.functional import cached_property
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from django.views.generic import (
|
||||
CreateView,
|
||||
DeleteView,
|
||||
DetailView,
|
||||
ListView,
|
||||
View,
|
||||
)
|
||||
|
||||
from pretix.base.i18n import language
|
||||
from pretix.base.middleware import add_to_response_csp
|
||||
from pretix.base.models.orders import OrderPosition
|
||||
from pretix.base.models.wallet import WalletLayout
|
||||
from pretix.base.services import tickets
|
||||
from pretix.base.services.tickets import get_preview_position
|
||||
from pretix.base.views.tasks import AsyncAction
|
||||
from pretix.base.wallet.placeholders import (
|
||||
get_wallet_placeholder_renderer,
|
||||
get_wallet_placeholders,
|
||||
)
|
||||
from pretix.base.wallet.platforms import (
|
||||
get_available_platforms,
|
||||
get_platform,
|
||||
pass_style_registry,
|
||||
wallet_platform_registry,
|
||||
)
|
||||
from pretix.base.wallet.tasks import get_pass
|
||||
from pretix.control.permissions import EventPermissionRequiredMixin
|
||||
from pretix.control.views.orders import OrderView
|
||||
from pretix.helpers.database import rolledback_transaction
|
||||
from pretix.helpers.i18n import localizable_to_dict
|
||||
from pretix.helpers.models import modelclone
|
||||
from pretix.control.forms.event import WalletLayoutCreateForm
|
||||
|
||||
|
||||
def get_editor_placeholders(event):
|
||||
with (
|
||||
rolledback_transaction(),
|
||||
language(event.settings.locale, event.settings.region),
|
||||
):
|
||||
p = get_preview_position(event)
|
||||
context = get_wallet_placeholder_renderer(order_position=p)
|
||||
placeholders = {
|
||||
t: {
|
||||
pid: {
|
||||
"label": (localizable_to_dict(p.label, event.settings.locales)),
|
||||
"sample": str(context.render_sample(p)),
|
||||
"required_context": list(sorted(p.required_context)),
|
||||
}
|
||||
for pid, p in ps.items()
|
||||
}
|
||||
for t, ps in get_wallet_placeholders(event).items()
|
||||
}
|
||||
return placeholders
|
||||
|
||||
|
||||
class WalletLayoutMixin:
|
||||
model = WalletLayout
|
||||
permission = "event.settings.general:write"
|
||||
pk_url_kwarg = "layout"
|
||||
context_object_name = "layouts"
|
||||
|
||||
def get_queryset(self):
|
||||
return self.request.event.wallet_layouts.all()
|
||||
|
||||
|
||||
class LayoutListView(WalletLayoutMixin, EventPermissionRequiredMixin, ListView):
|
||||
template_name = "pretixcontrol/wallet/layout_list.html"
|
||||
|
||||
|
||||
class LayoutDetailView(WalletLayoutMixin, EventPermissionRequiredMixin, DetailView):
|
||||
pass
|
||||
|
||||
|
||||
class LayoutEditorView(LayoutDetailView):
|
||||
template_name = "pretixcontrol/wallet/edit.html"
|
||||
|
||||
def get_context_data(self, **kwargs) -> dict[str, Any]:
|
||||
context = super().get_context_data(**kwargs)
|
||||
context["platforms"] = [
|
||||
{
|
||||
"identifier": platform.identifier,
|
||||
"name": platform.name,
|
||||
"styles": {
|
||||
style.identifier: style(self.request.event).asdict()
|
||||
for style, _meta in pass_style_registry.filter(
|
||||
active_in=self.request.event, platform=platform.identifier
|
||||
)
|
||||
},
|
||||
}
|
||||
for platform in sorted(
|
||||
get_available_platforms(self.request.event, show_disabled=True),
|
||||
key=lambda x: x.identifier,
|
||||
)
|
||||
]
|
||||
context["placeholders"] = get_editor_placeholders(self.request.event)
|
||||
context["locales"] = {
|
||||
l: dict(settings.LANGUAGES).get(l, l)
|
||||
for l in self.request.event.settings.get("locales")
|
||||
}
|
||||
|
||||
return context
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
response = super().dispatch(request, *args, **kwargs)
|
||||
add_to_response_csp(
|
||||
response,
|
||||
{
|
||||
"img-src": ["blob:"],
|
||||
},
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
class LayoutCreateView(WalletLayoutMixin, EventPermissionRequiredMixin, CreateView):
|
||||
template_name = "pretixcontrol/wallet/create.html"
|
||||
form_class = WalletLayoutCreateForm
|
||||
permission = "event.settings.general:write"
|
||||
|
||||
def form_valid(self, form):
|
||||
self.object = form.save()
|
||||
self.object.log_action(
|
||||
action="pretix.plugins.wallet.layout.created",
|
||||
user=self.request.user,
|
||||
data={
|
||||
**form.cleaned_data,
|
||||
"copy_from": self.copy_from.pk if self.copy_from else None,
|
||||
},
|
||||
)
|
||||
if self.copy_from:
|
||||
for pl in self.copy_from.platform_layouts.all():
|
||||
modelclone(pl, parent=self.object).save()
|
||||
else:
|
||||
for platform, _meta in wallet_platform_registry.filter(active_in=self.request.event):
|
||||
if not platform.default_style:
|
||||
continue
|
||||
style, _meta = pass_style_registry.get(active_in=self.request.event, identifier=(platform.identifier, platform.default_style))
|
||||
if not style:
|
||||
continue
|
||||
layout = style(self.request.event).default_layout
|
||||
self.object.platform_layouts.get_or_create(platform=platform.identifier, defaults={"style": style.identifier, "layout": layout})
|
||||
|
||||
return HttpResponseRedirect(self.get_success_url())
|
||||
|
||||
def get_form_kwargs(self) -> dict[str, Any]:
|
||||
kwargs = super().get_form_kwargs()
|
||||
kwargs["event"] = self.request.event
|
||||
|
||||
if self.copy_from:
|
||||
kwargs["instance"] = modelclone(self.copy_from, default=False)
|
||||
kwargs.setdefault("initial", {})
|
||||
|
||||
return kwargs
|
||||
|
||||
def get_success_url(self) -> str:
|
||||
return reverse(
|
||||
"control:event.wallet.edit",
|
||||
kwargs={
|
||||
"organizer": self.request.event.organizer.slug,
|
||||
"event": self.request.event.slug,
|
||||
"layout": self.object.pk,
|
||||
},
|
||||
)
|
||||
|
||||
@cached_property
|
||||
def copy_from(self) -> WalletLayout | None:
|
||||
if self.request.GET.get("copy_from"):
|
||||
try:
|
||||
return self.get_queryset().get(pk=self.request.GET.get("copy_from"))
|
||||
except WalletLayout.DoesNotExist:
|
||||
pass
|
||||
|
||||
|
||||
class LayoutPreviewView(EventPermissionRequiredMixin, View):
|
||||
permission = "event.settings.general:write"
|
||||
|
||||
def post(self, request, **kwargs):
|
||||
event = request.event
|
||||
platform_id = request.POST.get("platform")
|
||||
style_id = request.POST.get("style")
|
||||
layout = request.POST.get("layout")
|
||||
file_settings = json.loads(request.POST.get("file_settings"))
|
||||
base_layout = (
|
||||
event.wallet_layouts.get(pk=request.POST.get("id"))
|
||||
.platform_layouts.filter(platform=platform_id)
|
||||
.first()
|
||||
)
|
||||
|
||||
if base_layout:
|
||||
base_file_settings = {
|
||||
fs.key: fs.file for fs in base_layout.file_settings.all()
|
||||
}
|
||||
else:
|
||||
base_file_settings = {}
|
||||
|
||||
platform = get_platform(event, platform_id, show_disabled=True)
|
||||
if not platform:
|
||||
raise BadRequest("Unknown platform")
|
||||
|
||||
style, _meta = pass_style_registry.get(
|
||||
active_in=event, identifier=(platform_id, style_id)
|
||||
)
|
||||
if not style:
|
||||
raise BadRequest("Unknown style")
|
||||
|
||||
layout = json.loads(layout)
|
||||
with (
|
||||
rolledback_transaction(),
|
||||
language(request.event.settings.locale, request.event.settings.region),
|
||||
):
|
||||
p = get_preview_position(request.event)
|
||||
l = style(event=event, layout=layout)
|
||||
file_settings = {
|
||||
**base_file_settings,
|
||||
**l.extract_file_settings(request, file_settings),
|
||||
}
|
||||
layout = style(event, layout, file_settings)
|
||||
layout.validate()
|
||||
|
||||
result = platform.generate_preview(p, layout)
|
||||
if isinstance(result, str):
|
||||
return redirect(result)
|
||||
else:
|
||||
ext, mimet, data = result
|
||||
resp = HttpResponse(
|
||||
data,
|
||||
content_type=mimet,
|
||||
headers={
|
||||
"Content-Disposition": 'attachment; filename="ticket-preview.{}"'.format(
|
||||
ext.lstrip(".")
|
||||
)
|
||||
},
|
||||
)
|
||||
return resp
|
||||
|
||||
|
||||
class LayoutSetDefault(LayoutDetailView):
|
||||
@transaction.atomic
|
||||
def post(self, request, *args, **kwargs):
|
||||
obj = self.get_object()
|
||||
if not obj.default:
|
||||
for layout in request.event.wallet_layouts.filter(default=True):
|
||||
layout.log_action(
|
||||
"pretix.plugins.wallet.layout.changed",
|
||||
user=self.request.user,
|
||||
data={
|
||||
"default": False,
|
||||
},
|
||||
)
|
||||
layout.default = False
|
||||
layout.save(update_fields=["default"])
|
||||
obj.log_action(
|
||||
"pretix.plugins.wallet.layout.changed",
|
||||
user=self.request.user,
|
||||
data={
|
||||
"default": True,
|
||||
},
|
||||
)
|
||||
obj.default = True
|
||||
obj.save(update_fields=["default"])
|
||||
tickets.invalidate_cache.apply_async(
|
||||
kwargs={"event": self.request.event.pk, "provider": "wallet"}
|
||||
)
|
||||
messages.success(self.request, _("Your changes have been saved."))
|
||||
return redirect(self.get_success_url())
|
||||
|
||||
def get_success_url(self) -> str:
|
||||
return reverse(
|
||||
"control:event.wallet.index",
|
||||
kwargs={
|
||||
"organizer": self.request.event.organizer.slug,
|
||||
"event": self.request.event.slug,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class LayoutDelete(WalletLayoutMixin, DeleteView):
|
||||
template_name = "pretixcontrol/wallet/delete.html"
|
||||
|
||||
def get_success_url(self) -> str:
|
||||
return reverse(
|
||||
"control:event.wallet.index",
|
||||
kwargs={
|
||||
"organizer": self.request.event.organizer.slug,
|
||||
"event": self.request.event.slug,
|
||||
},
|
||||
)
|
||||
|
||||
@transaction.atomic
|
||||
def form_valid(self, form):
|
||||
self.object = self.get_object()
|
||||
if self.object.allow_delete():
|
||||
self.object.log_action(
|
||||
action="pretix.plugins.wallet.layout.deleted", user=self.request.user
|
||||
)
|
||||
self.object.delete()
|
||||
tickets.invalidate_cache.apply_async(
|
||||
kwargs={"event": self.request.event.pk, "provider": "wallet"}
|
||||
)
|
||||
messages.success(self.request, _("The selected layout been deleted."))
|
||||
else:
|
||||
messages.error(self.request, _("The selected layout cannot be deleted."))
|
||||
|
||||
return redirect(self.get_success_url())
|
||||
|
||||
|
||||
class OrderDownloadMixin:
|
||||
task = get_pass
|
||||
|
||||
def get_success_message(self, value):
|
||||
return ""
|
||||
|
||||
def get_success_url(self, value):
|
||||
return value
|
||||
|
||||
@cached_property
|
||||
def platform(self):
|
||||
if platform := self.kwargs.get("platform"):
|
||||
return get_platform(self.request.event, platform, show_disabled=True)
|
||||
|
||||
|
||||
class WalletGetView(OrderDownloadMixin, AsyncAction, OrderView):
|
||||
permission = "event.orders:read"
|
||||
|
||||
def get_error_url(self):
|
||||
return self.get_order_url()
|
||||
|
||||
@cached_property
|
||||
def order_position(self):
|
||||
try:
|
||||
return self.order.positions.get(pk=self.kwargs.get("position"))
|
||||
except OrderPosition.DoesNotExist:
|
||||
return None
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
if not self.platform:
|
||||
return self.error(_("You requested an invalid wallet platform."))
|
||||
if not self.order_position:
|
||||
raise Http404(
|
||||
_("Unknown order code or not authorized to access this order.")
|
||||
)
|
||||
|
||||
if "position" in kwargs:
|
||||
if not self.platform.is_available_for_position(self.order_position):
|
||||
return self.error(_("Ticket download is not enabled for this product."))
|
||||
return self.do(
|
||||
"orderposition", self.order_position.pk, self.platform.identifier, True
|
||||
)
|
||||
else:
|
||||
return self.do("order", self.order.pk, self.platform.identifier, True)
|
||||
@@ -19,12 +19,7 @@
|
||||
# You should have received a copy of the GNU Affero General Public License along with this program. If not, see
|
||||
# <https://www.gnu.org/licenses/>.
|
||||
#
|
||||
from typing import Union
|
||||
|
||||
from celery import Task
|
||||
from celery.result import AsyncResult
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import SuspiciousOperation
|
||||
|
||||
THRESHOLD_DOWNGRADE_TO_MID = 50
|
||||
THRESHOLD_DOWNGRADE_TO_LOW = 250
|
||||
@@ -65,27 +60,3 @@ def get_task_priority(shard, organizer_id):
|
||||
return settings.PRIORITY_CELERY_MID
|
||||
else:
|
||||
return settings.PRIORITY_CELERY_HIGH
|
||||
|
||||
|
||||
class SafeAsyncResult(AsyncResult):
|
||||
def __init__(self, *args, expected_task_name, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.__expected_task_name = expected_task_name
|
||||
|
||||
def _maybe_set_cache(self, meta):
|
||||
if meta and meta['status'] != "PENDING":
|
||||
if meta.get('name') != self.__expected_task_name:
|
||||
raise SuspiciousOperation(
|
||||
f"Received task result for {meta.get('name')!r}, but expected '{self.__expected_task_name}'"
|
||||
)
|
||||
return super()._maybe_set_cache(meta)
|
||||
|
||||
|
||||
def get_task_result(task_id: str, task_name: Union[Task, str]) -> SafeAsyncResult:
|
||||
"""
|
||||
Returns an AsyncResult by it's ID in a safe way, i.e. do not return anything if the task
|
||||
name does not match the expected task.
|
||||
"""
|
||||
if isinstance(task_name, Task):
|
||||
task_name = task_name.name
|
||||
return SafeAsyncResult(task_id, expected_task_name=task_name)
|
||||
@@ -25,7 +25,7 @@ import os
|
||||
import re
|
||||
from datetime import datetime
|
||||
from functools import lru_cache
|
||||
from typing import Optional
|
||||
from typing import Iterable, Optional
|
||||
|
||||
from django.apps import apps
|
||||
from django.conf import settings
|
||||
@@ -33,6 +33,8 @@ from django.utils import translation
|
||||
from django.utils.formats import get_format
|
||||
from django.utils.translation import to_locale
|
||||
|
||||
from pretix.base.i18n import MaybeTranslatedString
|
||||
|
||||
date_conversion_to_moment = {
|
||||
'%a': 'ddd',
|
||||
'%A': 'dddd',
|
||||
@@ -244,3 +246,13 @@ def parse_date_localized(date_str) -> Optional[datetime]:
|
||||
except (ValueError, TypeError):
|
||||
continue
|
||||
return dt
|
||||
|
||||
|
||||
def localizable_to_dict(string: MaybeTranslatedString, locales: Iterable[str]):
|
||||
translated = {}
|
||||
|
||||
for locale in locales:
|
||||
with translation.override(locale):
|
||||
translated[locale] = str(string)
|
||||
|
||||
return translated
|
||||
@@ -21,11 +21,13 @@
|
||||
#
|
||||
import copy
|
||||
from decimal import Decimal
|
||||
import typing
|
||||
|
||||
from django.core.files import File
|
||||
from django.db import models
|
||||
from django.db.models.fields import DecimalField
|
||||
|
||||
T = typing.TypeVar('T', bound=models.Model)
|
||||
|
||||
class Thumbnail(models.Model):
|
||||
source = models.CharField(max_length=255)
|
||||
@@ -47,6 +49,13 @@ def modelcopy(obj: models.Model, **kwargs):
|
||||
setattr(n, f.name, copy.deepcopy(val))
|
||||
return n
|
||||
|
||||
def modelclone(obj: T, **kwargs) -> T:
|
||||
new = copy.copy(obj)
|
||||
new.pk = None
|
||||
new._state.adding = True
|
||||
for k,v in kwargs.items():
|
||||
setattr(new, k, v)
|
||||
return new
|
||||
|
||||
# django 5 contains this in django.utils.choices.flatten_choices
|
||||
def flatten_choices(choices):
|
||||
|
||||
@@ -25,7 +25,6 @@ import types
|
||||
from datetime import datetime
|
||||
from http import cookies
|
||||
|
||||
from celery.backends.base import Backend
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import SuspiciousFileOperation
|
||||
from django.middleware.csrf import CsrfViewMiddleware as BaseCsrfMiddleware
|
||||
@@ -259,26 +258,6 @@ def monkeypatch_json_constants():
|
||||
del _CONSTANTS['NaN']
|
||||
|
||||
|
||||
def monkeypatch_celery_result_meta():
|
||||
"""
|
||||
We basically want `result_extended` from Celery to tie results to the tasks that created them,
|
||||
but just enabling `result_extended` will include full `args` and `kwargs` to the result which
|
||||
might contain large or sensitive data and we currently have no interest in storing them in the
|
||||
task backend without necessity.
|
||||
"""
|
||||
old__get_result_meta = Backend._get_result_meta
|
||||
|
||||
def new__get_result_meta(self, result, state, traceback, request, *args, **kwargs):
|
||||
meta = types.MethodType(old__get_result_meta, self)(
|
||||
result, state, traceback, request, *args, **kwargs,
|
||||
)
|
||||
if request and 'name' not in meta:
|
||||
meta['name'] = getattr(request, 'task', None)
|
||||
return meta
|
||||
|
||||
Backend._get_result_meta = new__get_result_meta
|
||||
|
||||
|
||||
def monkeypatch_all_at_ready():
|
||||
monkeypatch_vobject_performance()
|
||||
monkeypatch_pillow_safer()
|
||||
@@ -288,4 +267,3 @@ def monkeypatch_all_at_ready():
|
||||
monkeypatch_reportlab_imagereader()
|
||||
monkeypatch_csrf_middleware()
|
||||
monkeypatch_json_constants()
|
||||
monkeypatch_celery_result_meta()
|
||||
@@ -31,13 +31,13 @@ class SafeDownloadSigner(TimestampSigner):
|
||||
def get_token(request, answer):
|
||||
if not request.session.session_key:
|
||||
request.session.create()
|
||||
payload = '{}:{}:{}'.format(request.session.session_key, answer.pk, answer.file.name)
|
||||
payload = '{}:{}'.format(request.session.session_key, answer.pk)
|
||||
signer = SafeDownloadSigner()
|
||||
return signer.sign(hashlib.sha1(payload.encode()).hexdigest())
|
||||
|
||||
|
||||
def check_token(request, answer, token):
|
||||
payload = hashlib.sha1('{}:{}:{}'.format(request.session.session_key, answer.pk, answer.file.name).encode()).hexdigest()
|
||||
payload = hashlib.sha1('{}:{}'.format(request.session.session_key, answer.pk).encode()).hexdigest()
|
||||
signer = SafeDownloadSigner()
|
||||
try:
|
||||
return payload == signer.unsign(token, max_age=3600 * 24)
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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}"
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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/>.
|
||||
#
|
||||
@@ -0,0 +1,44 @@
|
||||
#
|
||||
# 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/>.
|
||||
#
|
||||
from django.apps import AppConfig
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
from pretix import __version__ as version
|
||||
|
||||
|
||||
class WalletApp(AppConfig):
|
||||
name = "pretix.plugins.apple_wallet"
|
||||
verbose_name = _("Apple Wallet")
|
||||
|
||||
class PretixPluginMeta:
|
||||
name = _("Apple Wallet")
|
||||
author = _("the pretix team")
|
||||
version = version
|
||||
category = "FORMAT"
|
||||
description = _(
|
||||
"Issue wallet passes apple wallet"
|
||||
)
|
||||
|
||||
def ready(self):
|
||||
from . import receivers # NOQA
|
||||
from . import platform # NOQA
|
||||
from . import styles # NOQA
|
||||
@@ -0,0 +1,74 @@
|
||||
import logging
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
from django import forms
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.core.files import File
|
||||
from django.core.files.uploadedfile import SimpleUploadedFile, UploadedFile
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
from pretix.control.forms import ClearableBasenameFileInput
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def validate_rsa_privkey(value: File):
|
||||
value = value.read().strip()
|
||||
if isinstance(value, bytes):
|
||||
value = value.decode()
|
||||
if not value:
|
||||
return
|
||||
if not re.match(
|
||||
r"^-----BEGIN( (RSA |ENCRYPTED )?PRIVATE KEY-----).*-----END\1$",
|
||||
value,
|
||||
re.DOTALL,
|
||||
):
|
||||
raise ValidationError(
|
||||
_(
|
||||
"This does not look like an RSA private key in PEM format (it misses the correct begin or end signifiers)"
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class CertificateFileField(forms.FileField):
|
||||
widget = ClearableBasenameFileInput
|
||||
|
||||
def clean(self, value, *args, **kwargs):
|
||||
value = super().clean(value, *args, **kwargs)
|
||||
if isinstance(value, UploadedFile):
|
||||
value.open("rb")
|
||||
value.seek(0)
|
||||
content = value.read()
|
||||
if (
|
||||
content.startswith(b"-----BEGIN CERTIFICATE-----")
|
||||
and b"-----BEGIN CERTIFICATE-----" in content
|
||||
):
|
||||
return SimpleUploadedFile("cert.pem", content, "text/plain")
|
||||
|
||||
openssl_cmd = [
|
||||
"openssl",
|
||||
"x509",
|
||||
"-inform",
|
||||
"DER",
|
||||
"-outform",
|
||||
"PEM",
|
||||
]
|
||||
process = subprocess.Popen(
|
||||
openssl_cmd,
|
||||
stderr=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
stdin=subprocess.PIPE,
|
||||
)
|
||||
process.stdin.write(content)
|
||||
pem, error = process.communicate()
|
||||
if process.returncode != 0:
|
||||
logger.info("Trying to convert a DER to PEM failed: {}".format(error))
|
||||
raise ValidationError(
|
||||
_(
|
||||
"This does not look like a X509 certificate in either PEM or DER format"
|
||||
),
|
||||
)
|
||||
|
||||
return SimpleUploadedFile("cert.pem", pem, "text/plain")
|
||||
return value
|
||||
@@ -0,0 +1,85 @@
|
||||
# Generated by Django 5.2.19 on 2026-11-16 16:18
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
(
|
||||
"pretixbase",
|
||||
"0312_walletlayout",
|
||||
),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name="AppleWalletDevice",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.BigAutoField(
|
||||
auto_created=True, primary_key=True, serialize=False
|
||||
),
|
||||
),
|
||||
("device_library_id", models.CharField(unique=True)),
|
||||
("push_token", models.CharField()),
|
||||
("last_push", models.DateTimeField(auto_now_add=True)),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name="CombinedAppleWalletPass",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.BigAutoField(
|
||||
auto_created=True, primary_key=True, serialize=False
|
||||
),
|
||||
),
|
||||
("file", models.FileField(max_length=255, null=True, upload_to="")),
|
||||
("created", models.DateTimeField(auto_now_add=True)),
|
||||
(
|
||||
"order",
|
||||
models.OneToOneField(
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
to="pretixbase.order",
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name="AppleWalletPass",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.BigAutoField(
|
||||
auto_created=True, primary_key=True, serialize=False
|
||||
),
|
||||
),
|
||||
("serial_number", models.CharField()),
|
||||
("pass_type", models.CharField()),
|
||||
("manifest", models.CharField()),
|
||||
("content", models.FileField(upload_to="")),
|
||||
("updated_at", models.DateTimeField(auto_now=True)),
|
||||
(
|
||||
"order_position",
|
||||
models.OneToOneField(
|
||||
on_delete=django.db.models.deletion.PROTECT,
|
||||
to="pretixbase.orderposition",
|
||||
),
|
||||
),
|
||||
(
|
||||
"registered_devices",
|
||||
models.ManyToManyField(
|
||||
related_name="passes", to="apple_wallet.applewalletdevice"
|
||||
),
|
||||
),
|
||||
],
|
||||
options={
|
||||
"unique_together": {("pass_type", "serial_number")},
|
||||
},
|
||||
),
|
||||
]
|
||||
Whitespace-only changes.
@@ -0,0 +1,105 @@
|
||||
#
|
||||
# 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/>.
|
||||
#
|
||||
|
||||
from django.db import models
|
||||
from django.utils.crypto import (
|
||||
constant_time_compare, get_random_string, salted_hmac,
|
||||
)
|
||||
|
||||
from pretix.base.models import OrderPosition
|
||||
from pretix.base.models.orders import Order
|
||||
|
||||
|
||||
class AppleWalletDevice(models.Model):
|
||||
device_library_id = models.CharField(unique=True)
|
||||
push_token = models.CharField()
|
||||
last_push = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
|
||||
class AppleWalletPassQuerySet(models.QuerySet):
|
||||
def get_by_auth_token(self, received_message):
|
||||
dummy = get_random_string(16)
|
||||
pk, received_token = received_message.split(":")
|
||||
|
||||
try:
|
||||
pass_obj = self.get(order_position__pk=pk)
|
||||
except AppleWalletPass.DoesNotExist:
|
||||
# Do a hash comparison as well to harden against timing attacks
|
||||
dummy_hash = salted_hmac(
|
||||
key_salt="pretix.plugins.wallet.AppleWalletPass.auth_token",
|
||||
algorithm="sha256",
|
||||
value=str(12345),
|
||||
secret=dummy,
|
||||
).hexdigest()
|
||||
constant_time_compare(
|
||||
dummy_hash,
|
||||
received_token,
|
||||
)
|
||||
raise AppleWalletPass.DoesNotExist
|
||||
|
||||
if constant_time_compare(
|
||||
pass_obj.auth_token,
|
||||
received_message,
|
||||
):
|
||||
return pass_obj
|
||||
else:
|
||||
raise AppleWalletPass.DoesNotExist
|
||||
|
||||
|
||||
class AppleWalletPass(models.Model):
|
||||
order_position = models.OneToOneField(OrderPosition, on_delete=models.PROTECT)
|
||||
|
||||
serial_number = models.CharField()
|
||||
pass_type = models.CharField()
|
||||
manifest = models.CharField()
|
||||
content = models.FileField()
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
registered_devices = models.ManyToManyField(
|
||||
AppleWalletDevice, related_name="passes"
|
||||
)
|
||||
|
||||
objects = AppleWalletPassQuerySet.as_manager()
|
||||
|
||||
class Meta:
|
||||
unique_together = [
|
||||
("pass_type", "serial_number"),
|
||||
]
|
||||
|
||||
@property
|
||||
def auth_token(self):
|
||||
return (
|
||||
str(self.order_position.pk)
|
||||
+ ":"
|
||||
+ salted_hmac(
|
||||
key_salt="pretix.plugins.wallet.AppleWalletPass.auth_token",
|
||||
algorithm="sha256",
|
||||
secret=self.order_position.web_secret,
|
||||
value=str(self.order_position.pk),
|
||||
).hexdigest()
|
||||
)
|
||||
|
||||
|
||||
class CombinedAppleWalletPass(models.Model):
|
||||
order = models.OneToOneField(Order, on_delete=models.CASCADE)
|
||||
file = models.FileField(null=True, blank=True, max_length=255)
|
||||
created = models.DateTimeField(auto_now_add=True)
|
||||
@@ -0,0 +1,272 @@
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import tempfile
|
||||
import zipfile
|
||||
from collections import OrderedDict
|
||||
|
||||
import cryptography
|
||||
import cryptography.hazmat.primitives.hashes
|
||||
import cryptography.hazmat.primitives.serialization.pkcs7
|
||||
import cryptography.x509
|
||||
from django import forms
|
||||
from django.core.files.base import ContentFile
|
||||
from django.utils.encoding import force_bytes
|
||||
from django.utils.functional import classproperty
|
||||
from django.utils.translation import gettext as _
|
||||
|
||||
from pretix.base.forms import SecretKeySettingsField
|
||||
from pretix.base.i18n import MaybeTranslatedString
|
||||
from pretix.base.models.orders import Order
|
||||
from pretix.base.wallet.platforms import (
|
||||
WalletPlatform, wallet_platform_registry,
|
||||
)
|
||||
from pretix.control.forms import ClearableBasenameFileInput
|
||||
from pretix.multidomain.urlreverse import eventreverse_absolute
|
||||
|
||||
from .forms import CertificateFileField, validate_rsa_privkey
|
||||
from .models import CombinedAppleWalletPass
|
||||
|
||||
logger = logging.getLogger("pretix.plugins.wallet.apple")
|
||||
|
||||
|
||||
@wallet_platform_registry.register
|
||||
class ApplePlatform(WalletPlatform):
|
||||
identifier = "apple"
|
||||
name = _("Apple Wallet")
|
||||
|
||||
@classmethod
|
||||
def get_global_settings(cls, **kwargs):
|
||||
return OrderedDict(
|
||||
[
|
||||
(
|
||||
# TODO: extract from pass certificate
|
||||
"wallet_apple_team_id",
|
||||
forms.CharField(
|
||||
label=_("Apple Wallet Pass team ID"),
|
||||
required=False,
|
||||
),
|
||||
),
|
||||
(
|
||||
# TODO: extract from pass certificate
|
||||
"wallet_apple_pass_type_id",
|
||||
forms.CharField(
|
||||
label=_("Apple Wallet Pass type"),
|
||||
required=False,
|
||||
),
|
||||
),
|
||||
(
|
||||
"wallet_apple_certificate",
|
||||
CertificateFileField(
|
||||
label=_("Apple Wallet Pass certificate file"),
|
||||
required=False,
|
||||
),
|
||||
),
|
||||
(
|
||||
# TODO: download this server-side
|
||||
"wallet_apple_ca_certificate",
|
||||
CertificateFileField(
|
||||
label=_("Apple Wallet Pass CA Certificate"),
|
||||
help_text=_(
|
||||
"You can download the current CA certificate from apple at "
|
||||
"https://www.apple.com/certificateauthority/AppleWWDRCAG4.cer"
|
||||
),
|
||||
required=False,
|
||||
),
|
||||
),
|
||||
(
|
||||
"wallet_apple_key",
|
||||
forms.FileField(
|
||||
label=_("Apple Wallet Pass secret key"),
|
||||
required=False,
|
||||
validators=[validate_rsa_privkey],
|
||||
widget=ClearableBasenameFileInput,
|
||||
),
|
||||
),
|
||||
(
|
||||
"wallet_apple_key_password",
|
||||
SecretKeySettingsField(
|
||||
label=_("Apple Wallet Pass key password"),
|
||||
required=False,
|
||||
help_text=_(
|
||||
"Optional, only necessary if the key entered above requires a password to use."
|
||||
),
|
||||
),
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
def generate(self, position, layout=None) -> str:
|
||||
if not layout:
|
||||
op_layout = self.get_layout(position)
|
||||
if not op_layout:
|
||||
raise ValueError(
|
||||
_(
|
||||
"WalletPlatform.generate called without layout and without position layout"
|
||||
)
|
||||
)
|
||||
layout = op_layout.pass_layout
|
||||
|
||||
layout.generate(position)
|
||||
|
||||
return eventreverse_absolute(
|
||||
self.event,
|
||||
"plugins:apple_wallet:download",
|
||||
kwargs={
|
||||
"order": position.order.code,
|
||||
"secret": position.order.secret,
|
||||
"position": position.pk,
|
||||
},
|
||||
)
|
||||
|
||||
def generate_preview(self, position, layout):
|
||||
pass_obj = layout.generate(position)
|
||||
data = pass_obj.content.file.read()
|
||||
pass_obj.content.delete()
|
||||
return "pkpass", "application/vnd.apple.pkpass", data
|
||||
|
||||
def generate_order(self, order: Order):
|
||||
with tempfile.TemporaryFile() as d:
|
||||
with zipfile.ZipFile(d, "w") as zipf:
|
||||
for pos in order.positions_with_tickets:
|
||||
if self.is_available_for_position(pos):
|
||||
layout = self.get_layout(pos)
|
||||
if not layout:
|
||||
raise ValueError(
|
||||
"Impossible: is_available_for_position==True but no layout"
|
||||
)
|
||||
|
||||
pass_obj = layout.pass_layout.generate(pos, False)
|
||||
zipf.writestr(
|
||||
"{}-{}.pkpass".format(order.code, pos.positionid),
|
||||
pass_obj.content.read(),
|
||||
)
|
||||
|
||||
d.seek(0)
|
||||
data = d.read()
|
||||
|
||||
if hasattr(order, "combinedapplewalletpass"):
|
||||
order.combinedapplewalletpass.delete()
|
||||
|
||||
ct = CombinedAppleWalletPass.objects.create(
|
||||
order=order,
|
||||
file=None,
|
||||
)
|
||||
ct.file.save(
|
||||
"{}-{}.pkpasses".format(order.code, self.identifier), ContentFile(data)
|
||||
)
|
||||
|
||||
return eventreverse_absolute(
|
||||
self.event,
|
||||
"plugins:apple_wallet:download_combined",
|
||||
kwargs={"order": order.code, "secret": order.secret},
|
||||
)
|
||||
|
||||
def is_available(self):
|
||||
for field in [
|
||||
"wallet_apple_team_id",
|
||||
"wallet_apple_pass_type_id",
|
||||
"wallet_apple_certificate",
|
||||
"wallet_apple_ca_certificate",
|
||||
"wallet_apple_key",
|
||||
]:
|
||||
if not self.event.settings.get(field):
|
||||
return False
|
||||
return super().is_available()
|
||||
|
||||
@classproperty
|
||||
def default_style(cls): # noqa: N805
|
||||
return "event_1"
|
||||
|
||||
|
||||
class StringResource:
|
||||
entries: dict[str, MaybeTranslatedString]
|
||||
locales: set[str]
|
||||
|
||||
def __init__(self, locales):
|
||||
self.entries = {}
|
||||
self.locales = set(locales)
|
||||
|
||||
def add_entry(self, key: str, value: MaybeTranslatedString):
|
||||
if key in self.entries:
|
||||
raise ValueError(f"{key} already exists in this StringResource")
|
||||
self.entries[key] = value
|
||||
|
||||
def escape(self, string):
|
||||
return string.translate(
|
||||
str.maketrans({'"': '\\"', "\r": "\\r", "\n": "\\n", "\\": "\\\\"})
|
||||
)
|
||||
|
||||
def generate_resource(self, language):
|
||||
output = ""
|
||||
for key, entry in self.entries.items():
|
||||
if isinstance(entry, str):
|
||||
output += f'"{self.escape(key)}" = "{self.escape(entry)}";\n'
|
||||
else:
|
||||
output += f'"{self.escape(key)}" = "{self.escape(entry.localize(language))}";\n'
|
||||
return output.strip()
|
||||
|
||||
def generate(self):
|
||||
return {language: self.generate_resource(language) for language in self.locales}
|
||||
|
||||
|
||||
class SignedZipFile:
|
||||
"""Generates a zip-file with manifest and signature as apple expects a pkpass file to be"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
ca_certificate: str | bytes,
|
||||
certificate: str | bytes,
|
||||
key: str | bytes,
|
||||
password,
|
||||
):
|
||||
self.ca_certificate = cryptography.x509.load_pem_x509_certificate(
|
||||
force_bytes(ca_certificate)
|
||||
)
|
||||
self.certificate = cryptography.x509.load_pem_x509_certificate(
|
||||
force_bytes(certificate)
|
||||
)
|
||||
self.key = cryptography.hazmat.primitives.serialization.load_pem_private_key(
|
||||
force_bytes(key), force_bytes(password) if password else None
|
||||
)
|
||||
self.password = password
|
||||
|
||||
self.file = io.BytesIO()
|
||||
self.zip_file = zipfile.ZipFile(self.file, "w")
|
||||
self.manifest = {}
|
||||
|
||||
def sign(self, data: bytes):
|
||||
return (
|
||||
cryptography.hazmat.primitives.serialization.pkcs7.PKCS7SignatureBuilder()
|
||||
.set_data(data)
|
||||
.add_signer(
|
||||
self.certificate,
|
||||
self.key,
|
||||
cryptography.hazmat.primitives.hashes.SHA256(),
|
||||
)
|
||||
.add_certificate(self.ca_certificate)
|
||||
.sign(
|
||||
cryptography.hazmat.primitives.serialization.Encoding.DER,
|
||||
[
|
||||
cryptography.hazmat.primitives.serialization.pkcs7.PKCS7Options.Binary,
|
||||
cryptography.hazmat.primitives.serialization.pkcs7.PKCS7Options.DetachedSignature,
|
||||
],
|
||||
)
|
||||
)
|
||||
|
||||
def finish(self):
|
||||
manifest = json.dumps(self.manifest).encode()
|
||||
signature = self.sign(manifest)
|
||||
self.add_file("manifest.json", manifest)
|
||||
self.add_file("signature", signature)
|
||||
self.zip_file.close()
|
||||
return self.file.getvalue(), manifest.decode()
|
||||
|
||||
def add_file(self, filename: str, content: str | bytes):
|
||||
if isinstance(content, str):
|
||||
content = content.encode()
|
||||
|
||||
with self.zip_file.open(filename, "w") as f:
|
||||
f.write(content)
|
||||
self.manifest[filename] = hashlib.sha1(content).hexdigest()
|
||||
@@ -0,0 +1,135 @@
|
||||
#
|
||||
# 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/>.
|
||||
#
|
||||
|
||||
from django.db.models import Exists, OuterRef
|
||||
from django.dispatch import receiver
|
||||
from django.template.loader import get_template
|
||||
from django.utils.translation import gettext as _
|
||||
|
||||
from pretix.base.models.event import Event
|
||||
from pretix.base.shredder import BaseDataShredder, slow_delete
|
||||
from pretix.base.signals import (
|
||||
invalidate_ticket_cache, periodic_task, register_data_shredders,
|
||||
)
|
||||
from pretix.base.wallet.tasks import get_pass
|
||||
from pretix.control.signals import html_head
|
||||
|
||||
from .models import AppleWalletDevice, AppleWalletPass, CombinedAppleWalletPass
|
||||
from .tasks import send_update_apns
|
||||
|
||||
|
||||
@receiver(periodic_task, dispatch_uid="wallet_periodic")
|
||||
def periodic_tasks(sender, **kwargs):
|
||||
send_update_apns.apply_async()
|
||||
|
||||
|
||||
@receiver(invalidate_ticket_cache, dispatch_uid="invalidate_ticket_cache_wallet_apple")
|
||||
def invalidate_apple(
|
||||
sender: Event, item: int | None, provider: str | None, order: int | None, **kwargs
|
||||
):
|
||||
if provider and provider != "wallet":
|
||||
return
|
||||
|
||||
pass_qs = AppleWalletPass.objects.filter(order_position__order__event=sender)
|
||||
passes_qs = CombinedAppleWalletPass.objects.filter(order__event=sender)
|
||||
|
||||
if item:
|
||||
pass_qs = pass_qs.filter(order_position__item_id=item)
|
||||
passes_qs = passes_qs.filter(order__all_positions__item_id=item)
|
||||
|
||||
if order:
|
||||
pass_qs = pass_qs.filter(order_position__order_id=order)
|
||||
passes_qs = passes_qs.filter(order_id=order)
|
||||
|
||||
for pass_obj in pass_qs:
|
||||
get_pass.apply_async(
|
||||
kwargs={
|
||||
"model": "orderposition",
|
||||
"pk": pass_obj.order_position_id,
|
||||
"platform_identifier": "apple",
|
||||
"show_disabled": False,
|
||||
}
|
||||
)
|
||||
|
||||
for passes_obj in passes_qs:
|
||||
passes_obj.delete()
|
||||
|
||||
|
||||
@receiver(html_head, dispatch_uid="html_head_apple_wallet")
|
||||
def html_head_apple_wallet(request, **kwargs):
|
||||
template = get_template("pretixplugins/apple_wallet/control_head.html")
|
||||
return template.render({})
|
||||
|
||||
|
||||
class AppleWalletShredder(BaseDataShredder):
|
||||
verbose_name = _("Apple Wallet")
|
||||
identifier = "apple_wallet"
|
||||
description = _(
|
||||
"This will remove all data regarding apple wallet passes. Passes can no longer be automatically updated "
|
||||
"after this data is deleted. No download will be offered."
|
||||
)
|
||||
|
||||
def generate_files(self):
|
||||
pass
|
||||
|
||||
def shred_data(self, progress_callback=None):
|
||||
qs_1 = AppleWalletDevice.objects.filter(
|
||||
Exists(
|
||||
AppleWalletPass.objects.filter(
|
||||
registered_devices=OuterRef("pk"),
|
||||
order_position__order__event=self.event,
|
||||
)
|
||||
),
|
||||
~Exists(
|
||||
AppleWalletPass.objects.filter(
|
||||
registered_devices=OuterRef("pk")
|
||||
).exclude(order_position__order__event=self.event)
|
||||
),
|
||||
)
|
||||
qs_1_count = qs_1.count()
|
||||
|
||||
qs_2 = AppleWalletPass.objects.filter(order_position__order__event=self.event)
|
||||
qs_2_count = qs_2.count()
|
||||
|
||||
qs_3 = CombinedAppleWalletPass.objects.filter(order__event=self.event)
|
||||
qs_3_count = qs_3.count()
|
||||
|
||||
total = qs_1_count + qs_2_count + qs_3_count
|
||||
|
||||
slow_delete(qs_1, progress_callback=progress_callback, progress_total=total)
|
||||
slow_delete(
|
||||
qs_2,
|
||||
progress_callback=progress_callback,
|
||||
progress_total=total,
|
||||
progress_offset=qs_1_count,
|
||||
)
|
||||
slow_delete(
|
||||
qs_3,
|
||||
progress_callback=progress_callback,
|
||||
progress_total=total,
|
||||
progress_offset=qs_1_count + qs_2_count,
|
||||
)
|
||||
|
||||
|
||||
@receiver(register_data_shredders, dispatch_uid="shredders_apple_wallet")
|
||||
def shredders_apple_wallet(**kwargs):
|
||||
return [AppleWalletShredder]
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
<script setup lang="ts">
|
||||
const props = defineProps<{
|
||||
fieldgroup: string;
|
||||
fieldgroupContents: Record<string, any>;
|
||||
}>()
|
||||
|
||||
function focusGroup () {
|
||||
// TODO: highlight group? or change ui concept completely
|
||||
const elem = document.getElementById('fieldgroup-' + props.fieldgroup)
|
||||
if (elem) {
|
||||
elem.scrollIntoView()
|
||||
}
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<template lang="pug">
|
||||
div(@click="focusGroup")
|
||||
div(v-for="entry in fieldgroupContents[fieldgroup]")
|
||||
div.pass-label {{ entry.label }}
|
||||
div.pass-content {{ entry.content }}
|
||||
</template>
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import type { PreviewProps } from '@/pretix/static/pretixcontrol/wallet/preview.d.ts'
|
||||
|
||||
import FieldGroupEntries from './FieldGroupEntries.vue'
|
||||
|
||||
const props = defineProps<PreviewProps>()
|
||||
|
||||
const theme = computed(() => {
|
||||
const theme = {
|
||||
bg_color: props.settings['bg_color'],
|
||||
fg_color: props.settings['fg_color'],
|
||||
label_color: props.settings['label_color'],
|
||||
bg_image: null,
|
||||
}
|
||||
const bg_image = props.settings['background']
|
||||
if (bg_image?.url) {
|
||||
theme.bg_image = `url(${encodeURI(props.settings['background'].url)})`
|
||||
theme.bg_color = '#000'
|
||||
theme.fg_color = '#fff'
|
||||
}
|
||||
return theme
|
||||
})
|
||||
|
||||
function focusGroup (identifier: string) {
|
||||
// TODO: highlight group? or change ui concept completely
|
||||
const elem = document.getElementById('fieldgroup-' + identifier)
|
||||
if (elem) {
|
||||
elem.scrollIntoView()
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template lang="pug">
|
||||
div.apple-pass-preview
|
||||
.pass-container.blur-bg.apple-pass-front
|
||||
.pass-inner.f-column
|
||||
.f-row.head-row
|
||||
img.logo(:src="settings['logo']?.url")
|
||||
div.logo-text {{ fieldgroupContents['logo_text']?.[0]?.content }}
|
||||
FieldGroupEntries.header.f-row(fieldgroup="header" :fieldgroupContents="fieldgroupContents")
|
||||
|
||||
.f-column
|
||||
FieldGroupEntries.primary(fieldgroup="primary" :fieldgroupContents="fieldgroupContents")
|
||||
FieldGroupEntries.f-row(fieldgroup="secondary" :fieldgroupContents="fieldgroupContents")
|
||||
FieldGroupEntries.f-row(fieldgroup="auxiliary" :fieldgroupContents="fieldgroupContents")
|
||||
|
||||
.qrcode-inner(v-for="qrcode in fieldgroupContents['code']" @click="focusGroup('code')") {{ qrcode.label }}
|
||||
|
||||
.pass-container.apple-pass-back
|
||||
FieldGroupEntries.pass-inner.f-column(fieldgroup="back" :fieldgroupContents="fieldgroupContents")
|
||||
|
||||
</template>
|
||||
|
||||
<style lang="css">
|
||||
.apple-pass-preview {
|
||||
display: grid;
|
||||
gap: 1em;
|
||||
grid-template-columns: repeat(auto-fit, minmax(auto, 360px));
|
||||
align-items: start;
|
||||
|
||||
.apple-pass-front {
|
||||
background-image: v-bind("theme.bg_image");
|
||||
background-color: v-bind("theme.bg_color");
|
||||
color: v-bind("theme.fg_color");
|
||||
background-size: cover;
|
||||
background-position: center;
|
||||
|
||||
padding-top: 0.25em;
|
||||
}
|
||||
|
||||
.pass-content {
|
||||
text-overflow: ellipsis;
|
||||
overflow: hidden;
|
||||
text-wrap: nowrap;
|
||||
}
|
||||
|
||||
.head-row {
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.logo {
|
||||
max-height: 3lh;
|
||||
object-fit: contain;
|
||||
flex-grow: 0;
|
||||
}
|
||||
.logo-text {
|
||||
font-size: 1.5em;
|
||||
font-weight: bold;
|
||||
min-height: 2lh;
|
||||
flex: 1 1;
|
||||
align-content: center;
|
||||
text-wrap: nowrap;
|
||||
}
|
||||
.header {
|
||||
flex: 1 0 fit-content;
|
||||
text-align: end;
|
||||
line-height: 1.25;
|
||||
gap: 0.25rem;
|
||||
justify-content: end;
|
||||
.pass-content {
|
||||
font-size: 1.25em;
|
||||
}
|
||||
}
|
||||
.primary {
|
||||
.pass-content {
|
||||
font-size: 1.5em;
|
||||
}
|
||||
}
|
||||
|
||||
.hero {
|
||||
align-self: center;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.apple-pass-front .pass-label {
|
||||
font-weight: bold;
|
||||
font-size: 0.8em;
|
||||
text-overflow: ellipsis;
|
||||
overflow: hidden;
|
||||
text-wrap: nowrap;
|
||||
|
||||
color: v-bind("theme.label_color");
|
||||
}
|
||||
|
||||
.apple-pass-back .pass-label {
|
||||
font-weight: bold;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,4 @@
|
||||
import Apple from './components/platform-preview/apple.vue'
|
||||
|
||||
window.pretix_wallet_preview_renderers = window.pretix_wallet_preview_renderers || {}
|
||||
window.pretix_wallet_preview_renderers['apple_eventticket'] = Apple
|
||||
@@ -0,0 +1,444 @@
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from django.core.files.base import ContentFile, File
|
||||
from django.db import transaction
|
||||
from django.utils.translation import gettext as _
|
||||
|
||||
from pretix.base.i18n import (
|
||||
FormattingLocalizableString, GettextLocalizableString,
|
||||
)
|
||||
from pretix.base.models import OrderPosition
|
||||
from pretix.base.wallet.platforms import pass_style_registry
|
||||
from pretix.base.wallet.platforms.base import (
|
||||
FieldGroup, FieldGroupDisplay, PassStyle, PlaceholderFieldEntry,
|
||||
TextFieldGroup,
|
||||
)
|
||||
from pretix.base.wallet.platforms.settings import (
|
||||
ColorSettingsField, FloatSettingsField, ImageSettingsField, convert_to_png,
|
||||
)
|
||||
from pretix.helpers import OF_SELF
|
||||
from pretix.multidomain.urlreverse import eventreverse_absolute
|
||||
|
||||
from .models import AppleWalletPass
|
||||
from .platform import ApplePlatform, SignedZipFile, StringResource
|
||||
|
||||
logger = logging.getLogger("pretix.plugins.apple_wallet")
|
||||
|
||||
|
||||
class AppleWalletStyle(PassStyle):
|
||||
platform = ApplePlatform
|
||||
|
||||
@property
|
||||
def settings(self):
|
||||
return [
|
||||
ImageSettingsField(
|
||||
identifier="logo",
|
||||
label=_("Logo"),
|
||||
help_text=_("Will be displayed on the top left corner of the pass"),
|
||||
default=self.event.settings.get('logo_image', as_type=File, binary_file=True)
|
||||
or "pretixbase/img/pretix-logo.png",
|
||||
),
|
||||
ImageSettingsField(
|
||||
identifier="icon",
|
||||
label=_("Icon"),
|
||||
help_text=_("Will be displayed as the file icon"),
|
||||
default="pretixbase/img/pretix-icon.png",
|
||||
),
|
||||
ImageSettingsField(identifier="background", label=_("Background Image")),
|
||||
ColorSettingsField(
|
||||
identifier="bg_color",
|
||||
label=_("Background Color"),
|
||||
),
|
||||
ColorSettingsField(
|
||||
identifier="fg_color",
|
||||
label=_("Foreground Color"),
|
||||
help_text=_(
|
||||
"This color is ignored if a background image is set. Instead, the text will be displayed in white."
|
||||
),
|
||||
default=self.event.settings.primary_color,
|
||||
),
|
||||
ColorSettingsField(
|
||||
identifier="label_color", label=_("Label Color"), default="#000000"
|
||||
),
|
||||
FloatSettingsField(
|
||||
identifier="lat",
|
||||
label=_("Latitude"),
|
||||
min=-90,
|
||||
max=90,
|
||||
default=self.event.geo_lat,
|
||||
),
|
||||
FloatSettingsField(
|
||||
identifier="long",
|
||||
label=_("Longitude"),
|
||||
min=-180,
|
||||
max=180,
|
||||
default=self.event.geo_lon,
|
||||
),
|
||||
]
|
||||
|
||||
def pass_content(self, fields, strings):
|
||||
raise NotImplementedError()
|
||||
|
||||
def generate_pass_json(
|
||||
self, fields, op, strings, pass_type, team_id, serial_number, auth_token
|
||||
):
|
||||
event = op.subevent or op.order.event
|
||||
tz = event.timezone
|
||||
|
||||
ticket = (
|
||||
FormattingLocalizableString(
|
||||
"{name} - {variation}", name=op.item.name, variation=op.variation.value
|
||||
)
|
||||
if op.variation
|
||||
else op.item.name
|
||||
)
|
||||
|
||||
description = FormattingLocalizableString(
|
||||
GettextLocalizableString.gettext("Ticket for {event} ({product})"),
|
||||
event=self.event.name,
|
||||
product=ticket,
|
||||
)
|
||||
strings.add_entry("description", description)
|
||||
|
||||
pass_json = {
|
||||
"formatVersion": 1,
|
||||
"description": "description",
|
||||
"organizationName": self.event.organizer.name,
|
||||
"passTypeIdentifier": pass_type,
|
||||
"teamIdentifier": team_id,
|
||||
"serialNumber": serial_number,
|
||||
"webServiceURL": eventreverse_absolute(self.event, "presale:event.index")
|
||||
+ "_wallet/apple/",
|
||||
"authenticationToken": auth_token,
|
||||
**self.pass_content(fields, strings),
|
||||
}
|
||||
|
||||
# TODO: Apples specs says this should be "specified as a CSS-style RGB triple, such as rgb(100, 10, 110).", but hex codes work as well
|
||||
if bg_color := self.get_cleaned_setting("bg_color"):
|
||||
pass_json["backgroundColor"] = bg_color
|
||||
if fg_color := self.get_cleaned_setting("fg_color"):
|
||||
pass_json["foregroundColor"] = fg_color
|
||||
if label_color := self.get_cleaned_setting("label_color"):
|
||||
pass_json["labelColor"] = label_color
|
||||
|
||||
if self.get_cleaned_setting("background"):
|
||||
# iOS ignores the set foregroundColor if a background is set and uses white instead.
|
||||
# Explicitly set white in this case so the pass looks the same on all platforms
|
||||
# https://developer.apple.com/forums/thread/809417
|
||||
pass_json["foregroundColor"] = "#ffffff"
|
||||
# macOS always shows transparency as black, iOS as backgroundColor.
|
||||
# Explicitly set black in this case so the pass looks the same on all platforms
|
||||
pass_json["backgroundColor"] = "#000000"
|
||||
|
||||
if "expirationDate" not in pass_json:
|
||||
if op.valid_until:
|
||||
pass_json["expirationDate"] = op.valid_until.astimezone(tz).isoformat()
|
||||
elif event.settings.show_date_to and event.date_to:
|
||||
pass_json["expirationDate"] = event.date_to.astimezone(tz).isoformat()
|
||||
|
||||
if "relevantDates" not in pass_json:
|
||||
if op.valid_from and op.valid_to:
|
||||
pass_json["relevantDates"] = [
|
||||
{
|
||||
"startDate": op.valid_from.astimezone(tz).isoformat(),
|
||||
"endDate": op.valid_to.astimezone(tz).isoformat(),
|
||||
}
|
||||
]
|
||||
elif op.valid_from:
|
||||
pass_json["relevantDates"] = [
|
||||
{"date": op.valid_from.astimezone(tz).isoformat()}
|
||||
]
|
||||
elif event.settings.show_date_to and event.date_to:
|
||||
pass_json["relevantDates"] = [
|
||||
{
|
||||
"startDate": event.date_from.astimezone(tz).isoformat(),
|
||||
"endDate": event.date_to.astimezone(tz).isoformat(),
|
||||
}
|
||||
]
|
||||
else:
|
||||
pass_json["relevantDates"] = [
|
||||
{"date": event.date_from.astimezone(tz).isoformat()}
|
||||
]
|
||||
|
||||
# TODO: also fill relevantDates from program times
|
||||
|
||||
if "locations" not in pass_json:
|
||||
if (lat := self.get_cleaned_setting("lat")) and (
|
||||
long := self.get_cleaned_setting("long")
|
||||
):
|
||||
pass_json["locations"] = {
|
||||
"latitude": lat,
|
||||
"longitude": long,
|
||||
}
|
||||
|
||||
return pass_json
|
||||
|
||||
@transaction.atomic
|
||||
def generate(self, op: OrderPosition, preview: bool = False):
|
||||
pass_type = self.event.settings.wallet_apple_pass_type_id
|
||||
team_id = self.event.settings.wallet_apple_team_id
|
||||
serial_number = "%s-%s-%s-%d" % (
|
||||
self.event.organizer.slug,
|
||||
self.event.slug,
|
||||
op.order.code,
|
||||
op.pk,
|
||||
)
|
||||
|
||||
if preview:
|
||||
pass_obj = AppleWalletPass(
|
||||
order_position=op, pass_type=pass_type, serial_number=serial_number
|
||||
)
|
||||
else:
|
||||
pass_obj, _ = AppleWalletPass.objects.select_for_update(
|
||||
of=OF_SELF
|
||||
).get_or_create(
|
||||
order_position=op,
|
||||
pass_type=pass_type,
|
||||
defaults={
|
||||
"serial_number": serial_number,
|
||||
},
|
||||
)
|
||||
|
||||
order = op.order
|
||||
filename = "{}-{}.pkpass".format(order.event.slug, order.code)
|
||||
|
||||
fields = self.get_pass_fields(op)
|
||||
pkpass = SignedZipFile(
|
||||
self.event.settings.wallet_apple_ca_certificate.read(),
|
||||
self.event.settings.wallet_apple_certificate.read(),
|
||||
self.event.settings.wallet_apple_key.read(),
|
||||
self.event.settings.wallet_apple_key_password,
|
||||
)
|
||||
strings = StringResource(locales=self.event.settings.locales)
|
||||
|
||||
pass_json = self.generate_pass_json(
|
||||
fields,
|
||||
op,
|
||||
strings,
|
||||
pass_type,
|
||||
team_id,
|
||||
pass_obj.serial_number,
|
||||
pass_obj.auth_token,
|
||||
)
|
||||
|
||||
if file := self.get_cleaned_setting("logo"):
|
||||
logo = convert_to_png(
|
||||
file, (480, 150)
|
||||
) # TODO: check max_size against apple HIG
|
||||
|
||||
if file := self.get_cleaned_setting("icon"):
|
||||
icon = convert_to_png(
|
||||
file, max_size=(87, 87)
|
||||
) # TODO: check max_size against apple HIG
|
||||
|
||||
pkpass.add_file("icon.png", icon.read())
|
||||
pkpass.add_file("logo.png", logo.read())
|
||||
|
||||
if file := self.get_cleaned_setting("background"):
|
||||
background = convert_to_png(
|
||||
file, max_size=(540, 660)
|
||||
) # TODO: check max_size against apple HIG
|
||||
pkpass.add_file("background.png", background.read())
|
||||
|
||||
for lang, content in strings.generate().items():
|
||||
pkpass.add_file(f"{lang}.lproj/pass.strings", content)
|
||||
pkpass.add_file("pass.json", json.dumps(pass_json))
|
||||
result, manifest = pkpass.finish()
|
||||
|
||||
if preview:
|
||||
pass_obj.content.file = ContentFile(result, name=filename)
|
||||
else:
|
||||
if pass_obj.content and pass_obj.manifest != manifest:
|
||||
pass_obj.content.delete()
|
||||
|
||||
if pass_obj.manifest != manifest:
|
||||
pass_obj.content.save(filename, ContentFile(result, name=filename))
|
||||
pass_obj.manifest = manifest
|
||||
pass_obj.save()
|
||||
|
||||
return pass_obj
|
||||
|
||||
|
||||
@pass_style_registry.register
|
||||
class AppleWalletEventTicket(AppleWalletStyle):
|
||||
identifier = "event_1"
|
||||
name = _("Event Ticket Layout")
|
||||
|
||||
@property
|
||||
def fieldgroups(self) -> list[FieldGroup]:
|
||||
return [
|
||||
TextFieldGroup(
|
||||
identifier="logo_text",
|
||||
name=_("Logo text"),
|
||||
max_entries=1,
|
||||
display=FieldGroupDisplay.PLAIN,
|
||||
context_args={"order_position"},
|
||||
can_overflow=False,
|
||||
),
|
||||
TextFieldGroup(
|
||||
identifier="header",
|
||||
name=_("Header"),
|
||||
max_entries=3,
|
||||
context_args={"order_position"},
|
||||
default_entries=[
|
||||
PlaceholderFieldEntry(
|
||||
content="admission_or_date_from",
|
||||
label=GettextLocalizableString.gettext("Admission"),
|
||||
),
|
||||
],
|
||||
default_overflow="back",
|
||||
),
|
||||
TextFieldGroup(
|
||||
identifier="primary",
|
||||
name=_("Primary"),
|
||||
min_entries=1,
|
||||
max_entries=1,
|
||||
default_entries=[
|
||||
PlaceholderFieldEntry(
|
||||
content="event",
|
||||
)
|
||||
],
|
||||
description=_("These fields appear prominently featured on the pass."),
|
||||
required=True,
|
||||
context_args={"order_position"},
|
||||
default_overflow="back",
|
||||
),
|
||||
TextFieldGroup(
|
||||
identifier="secondary",
|
||||
name=_("Secondary"),
|
||||
max_entries=4,
|
||||
context_args={"order_position"},
|
||||
default_entries=[
|
||||
PlaceholderFieldEntry(
|
||||
content="item_with_variation",
|
||||
label=GettextLocalizableString.gettext("Product"),
|
||||
)
|
||||
],
|
||||
default_overflow="back",
|
||||
),
|
||||
# TODO: validation of max field count if combined "Coupons, store cards, and generic passes
|
||||
# with a square barcode can have a total of up to four secondary and auxiliary fields, combined."
|
||||
TextFieldGroup(
|
||||
identifier="auxiliary",
|
||||
name=_("Auxiliary"),
|
||||
max_entries=4,
|
||||
context_args={"order_position"},
|
||||
default_entries=[
|
||||
PlaceholderFieldEntry(
|
||||
content="seat",
|
||||
label=GettextLocalizableString.gettext("Seat"),
|
||||
),
|
||||
PlaceholderFieldEntry(
|
||||
content="attendee_name",
|
||||
),
|
||||
PlaceholderFieldEntry(
|
||||
content="program_start",
|
||||
label=GettextLocalizableString.gettext("From"),
|
||||
),
|
||||
PlaceholderFieldEntry(
|
||||
content="program_end",
|
||||
label=GettextLocalizableString.gettext("To"),
|
||||
),
|
||||
],
|
||||
default_overflow="back",
|
||||
),
|
||||
TextFieldGroup(
|
||||
identifier="code",
|
||||
name=_("QR-Code"),
|
||||
max_entries=1,
|
||||
display=FieldGroupDisplay.PLAIN,
|
||||
default_entries=[
|
||||
PlaceholderFieldEntry(
|
||||
content="secret",
|
||||
)
|
||||
],
|
||||
context_args={"order_position"},
|
||||
),
|
||||
TextFieldGroup(
|
||||
identifier="back",
|
||||
name=_("Back"),
|
||||
context_args={"order_position"},
|
||||
default_entries=[
|
||||
PlaceholderFieldEntry(
|
||||
content="admission",
|
||||
),
|
||||
PlaceholderFieldEntry(
|
||||
content="attendee_name",
|
||||
),
|
||||
PlaceholderFieldEntry(
|
||||
content="order_email",
|
||||
label=GettextLocalizableString.gettext("Ordered by"),
|
||||
),
|
||||
PlaceholderFieldEntry(
|
||||
content="organizer",
|
||||
),
|
||||
PlaceholderFieldEntry(
|
||||
content="organizer_contact",
|
||||
),
|
||||
PlaceholderFieldEntry(
|
||||
content="order_code",
|
||||
),
|
||||
PlaceholderFieldEntry(
|
||||
content="purchase_date",
|
||||
),
|
||||
PlaceholderFieldEntry(
|
||||
content="website",
|
||||
),
|
||||
],
|
||||
),
|
||||
]
|
||||
|
||||
@property
|
||||
def preview_renderer(self) -> str | None:
|
||||
return "apple_eventticket"
|
||||
|
||||
def convert_fields(self, strings, fields, prefix):
|
||||
# TODO: detect if a string-value/string-label is the same as a generated field name
|
||||
# eg if a placeholder returns "primary-0-label", this would not be shown to the user but instead replaces with the label
|
||||
converted = []
|
||||
for i, f in enumerate(fields):
|
||||
converted_field = {**f, "key": f"{prefix}-{i}"}
|
||||
if "label" in converted_field:
|
||||
strings.add_entry(f"{prefix}-{i}-label", converted_field["label"])
|
||||
converted_field["label"] = f"{prefix}-{i}-label"
|
||||
|
||||
strings.add_entry(f"{prefix}-{i}-value", converted_field["value"])
|
||||
converted_field["value"] = f"{prefix}-{i}-value"
|
||||
converted.append(converted_field)
|
||||
return converted
|
||||
|
||||
def pass_content(self, fields, strings):
|
||||
content: dict[str, Any] = {
|
||||
"eventTicket": {
|
||||
"primaryFields": self.convert_fields(
|
||||
strings, fields["primary"], "primary"
|
||||
),
|
||||
"secondaryFields": self.convert_fields(
|
||||
strings, fields["secondary"], "secondary"
|
||||
),
|
||||
"auxiliaryFields": self.convert_fields(
|
||||
strings, fields["auxiliary"], "auxiliary"
|
||||
),
|
||||
"backFields": self.convert_fields(strings, fields["back"], "back"),
|
||||
"headerFields": self.convert_fields(
|
||||
strings, fields["header"], "header"
|
||||
),
|
||||
},
|
||||
}
|
||||
if fields["logo_text"]:
|
||||
content["logoText"] = self.convert_fields(
|
||||
strings, fields["logo_text"], "logo_text"
|
||||
)[0]["value"]
|
||||
|
||||
if fields["code"]:
|
||||
content["barcodes"] = [
|
||||
{
|
||||
"format": "PKBarcodeFormatQR",
|
||||
"message": str(fields["code"][0]["value"]),
|
||||
"messageEncoding": "utf-8",
|
||||
"altText": str(fields["code"][0]["value"]),
|
||||
}
|
||||
]
|
||||
return content
|
||||
@@ -0,0 +1,72 @@
|
||||
import ssl
|
||||
import tempfile
|
||||
|
||||
import httpx
|
||||
from django.db.models import Exists, OuterRef
|
||||
from django.utils.timezone import now
|
||||
from django_scopes import scopes_disabled
|
||||
|
||||
from pretix.base.models import Event
|
||||
from pretix.celery_app import app
|
||||
|
||||
from .models import AppleWalletDevice, AppleWalletPass
|
||||
|
||||
|
||||
@app.task
|
||||
@scopes_disabled()
|
||||
def send_update_apns():
|
||||
events_to_push = Event.objects.filter(
|
||||
plugins__icontains="pretix.plugins.apple_wallet"
|
||||
).filter(
|
||||
Exists(
|
||||
AppleWalletDevice.objects.filter(
|
||||
Exists(
|
||||
AppleWalletPass.objects.filter(
|
||||
registered_devices=OuterRef("pk"),
|
||||
updated_at__gte=OuterRef("last_push"),
|
||||
order_position__order__event=OuterRef(OuterRef("pk")),
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
for event in events_to_push:
|
||||
devices_to_push = AppleWalletDevice.objects.filter(
|
||||
Exists(
|
||||
AppleWalletPass.objects.filter(
|
||||
registered_devices=OuterRef("pk"),
|
||||
updated_at__gte=OuterRef("last_push"),
|
||||
order_position__order__event=event,
|
||||
)
|
||||
)
|
||||
)
|
||||
if not devices_to_push.exists():
|
||||
return
|
||||
|
||||
ca_cert = event.settings.wallet_apple_certificate.read()
|
||||
cert = event.settings.wallet_apple_certificate.read()
|
||||
key = event.settings.wallet_apple_key.read()
|
||||
|
||||
ctx = ssl.create_default_context()
|
||||
|
||||
with tempfile.NamedTemporaryFile("w") as certfile:
|
||||
certfile.write(key)
|
||||
certfile.write("\n")
|
||||
certfile.write(cert)
|
||||
certfile.write("\n")
|
||||
certfile.write(ca_cert)
|
||||
certfile.flush()
|
||||
ctx.load_cert_chain(
|
||||
certfile=certfile.name,
|
||||
password=event.settings.wallet_apple_key_password,
|
||||
)
|
||||
|
||||
client = httpx.Client(verify=ctx, http1=False, http2=True)
|
||||
|
||||
for device in devices_to_push:
|
||||
device.last_push = now()
|
||||
client.post(
|
||||
f"https://api.push.apple.com/3/device/{device.push_token}", json={}
|
||||
)
|
||||
device.save()
|
||||
@@ -0,0 +1,3 @@
|
||||
{% load vite %}
|
||||
|
||||
{% vite_asset "src/pretix/plugins/apple_wallet/static/pretixplugins/apple_wallet/main.ts" %}
|
||||
@@ -0,0 +1,60 @@
|
||||
#
|
||||
# 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/>.
|
||||
#
|
||||
from django.urls import re_path
|
||||
|
||||
from .views import (
|
||||
DeviceGetUpdatablePassesView, DeviceRegistrationView,
|
||||
DownloadCombinedPassView, DownloadPassView, GetPassView, LogView,
|
||||
)
|
||||
|
||||
event_patterns = [
|
||||
re_path(
|
||||
r"_wallet/apple/v1/devices/(?P<device_library_identifier>[^/]+)/registrations/(?P<pass_type_identifier>[^/]+)/(?P<serial_number>[^/]+)$",
|
||||
DeviceRegistrationView.as_view(),
|
||||
name="apple_register",
|
||||
),
|
||||
re_path(
|
||||
r"_wallet/apple/v1/devices/(?P<device_library_identifier>[^/]+)/registrations/(?P<pass_type_identifier>[^/]+)$",
|
||||
DeviceGetUpdatablePassesView.as_view(),
|
||||
name="apple_get-updatable",
|
||||
),
|
||||
re_path(
|
||||
r"_wallet/apple/v1/passes/(?P<pass_type_identifier>[^/]+)/(?P<serial_number>[^/]+)$",
|
||||
GetPassView.as_view(),
|
||||
name="apple_get-pass",
|
||||
),
|
||||
re_path(
|
||||
r"_wallet/apple/v1/log$",
|
||||
LogView.as_view(),
|
||||
name="apple_log",
|
||||
),
|
||||
re_path(
|
||||
r"^order/(?P<order>[^/]+)/(?P<secret>[A-Za-z0-9]+)/wallet/apple/download/(?P<position>[0-9]+)/$",
|
||||
DownloadPassView.as_view(),
|
||||
name="download",
|
||||
),
|
||||
re_path(
|
||||
r"^order/(?P<order>[^/]+)/(?P<secret>[A-Za-z0-9]+)/wallet/apple/download/$",
|
||||
DownloadCombinedPassView.as_view(),
|
||||
name="download_combined",
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,209 @@
|
||||
import datetime
|
||||
import logging
|
||||
from functools import cached_property
|
||||
|
||||
from django.contrib.auth.models import AnonymousUser
|
||||
from django.http.response import Http404
|
||||
from django.shortcuts import get_object_or_404
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.utils.translation import gettext as _
|
||||
from django.views import View
|
||||
from django.views.decorators.http import condition
|
||||
from rest_framework import exceptions, permissions, serializers
|
||||
from rest_framework.authentication import (
|
||||
BaseAuthentication, get_authorization_header,
|
||||
)
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
|
||||
from pretix.base.models.orders import OrderPosition
|
||||
from pretix.helpers.http import ChunkBasedFileResponse
|
||||
from pretix.presale.views import EventViewMixin
|
||||
from pretix.presale.views.order import OrderDetailMixin
|
||||
|
||||
from .models import AppleWalletDevice, AppleWalletPass, CombinedAppleWalletPass
|
||||
|
||||
logger = logging.getLogger("pretix.plugins.apple_wallet")
|
||||
|
||||
|
||||
class ApplePassAuthentication(BaseAuthentication):
|
||||
keyword = "ApplePass"
|
||||
model = AppleWalletPass
|
||||
|
||||
def authenticate(self, request):
|
||||
auth = get_authorization_header(request).split()
|
||||
|
||||
if not auth or auth[0].lower() != self.keyword.lower().encode():
|
||||
return None
|
||||
|
||||
if len(auth) == 1:
|
||||
msg = _("Invalid token header. No credentials provided.")
|
||||
raise exceptions.AuthenticationFailed(msg)
|
||||
elif len(auth) > 2:
|
||||
msg = _("Invalid token header. Token string should not contain spaces.")
|
||||
raise exceptions.AuthenticationFailed(msg)
|
||||
|
||||
try:
|
||||
token = auth[1].decode()
|
||||
except UnicodeError:
|
||||
msg = _(
|
||||
"Invalid token header. Token string should not contain invalid characters."
|
||||
)
|
||||
raise exceptions.AuthenticationFailed(msg)
|
||||
|
||||
if ":" not in token:
|
||||
msg = _(
|
||||
"Invalid token header. Missing seperator."
|
||||
)
|
||||
raise exceptions.AuthenticationFailed(msg)
|
||||
|
||||
try:
|
||||
pass_obj = AppleWalletPass.objects.get_by_auth_token(
|
||||
token
|
||||
)
|
||||
except AppleWalletPass.DoesNotExist:
|
||||
raise exceptions.AuthenticationFailed(_("Invalid token."))
|
||||
|
||||
return (AnonymousUser(), pass_obj)
|
||||
|
||||
def authenticate_header(self, request):
|
||||
return self.keyword
|
||||
|
||||
|
||||
class ApplePassPermission(permissions.BasePermission):
|
||||
def has_permission(self, request, view):
|
||||
if not isinstance(request.auth, AppleWalletPass):
|
||||
return False
|
||||
pass_obj = request.auth
|
||||
if pass_obj.serial_number != view.kwargs["serial_number"]:
|
||||
return False
|
||||
if (
|
||||
request.event.settings.wallet_apple_pass_type_id
|
||||
!= view.kwargs["pass_type_identifier"]
|
||||
):
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
class RegisterPassSerializer(serializers.Serializer):
|
||||
push_token = serializers.CharField()
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.fields["push_token"].field_name = "pushToken"
|
||||
|
||||
|
||||
class LogEntrySerializer(serializers.Serializer):
|
||||
logs = serializers.ListField()
|
||||
|
||||
|
||||
class DeviceRegistrationView(APIView):
|
||||
authentication_classes = [ApplePassAuthentication]
|
||||
permission_classes = [ApplePassPermission]
|
||||
|
||||
def post(self, request, *args, device_library_identifier, **kwargs):
|
||||
serializer = RegisterPassSerializer(data=request.data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
|
||||
device, _ = AppleWalletDevice.objects.get_or_create(
|
||||
device_library_id=device_library_identifier,
|
||||
defaults={"push_token": serializer.data["pushToken"]},
|
||||
)
|
||||
device.passes.add(request.auth)
|
||||
return Response({})
|
||||
|
||||
def delete(self, request, *args, device_library_identifier, **kwargs):
|
||||
try:
|
||||
device = AppleWalletDevice.objects.get(
|
||||
device_library_id=device_library_identifier,
|
||||
)
|
||||
except AppleWalletDevice.DoesNotExist:
|
||||
return Response({})
|
||||
device.passes.remove(request.auth)
|
||||
if not device.passes.exists():
|
||||
device.delete()
|
||||
|
||||
return Response({})
|
||||
|
||||
|
||||
class DeviceGetUpdatablePassesView(APIView):
|
||||
authentication_classes = ()
|
||||
permission_classes = ()
|
||||
|
||||
def get(
|
||||
self, request, *args, device_library_identifier, pass_type_identifier, **kwargs
|
||||
):
|
||||
try:
|
||||
device = AppleWalletDevice.objects.get(
|
||||
device_library_id=device_library_identifier,
|
||||
)
|
||||
except AppleWalletDevice.DoesNotExist:
|
||||
raise exceptions.NotFound(_("Unknown device library identifier."))
|
||||
|
||||
passes = device.passes.filter(pass_type=pass_type_identifier)
|
||||
try:
|
||||
last_update = datetime.datetime.fromtimestamp(int(request.GET.get("passesUpdatedSince", 0)), datetime.UTC)
|
||||
passes = passes.filter(
|
||||
updated_at__gt=last_update
|
||||
)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
return Response(
|
||||
{
|
||||
"serialNumbers": passes.values_list("serial_number", flat=True),
|
||||
"lastUpdated": str(int(datetime.datetime.now(datetime.UTC).timestamp())),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class GetPassView(APIView):
|
||||
authentication_classes = [ApplePassAuthentication]
|
||||
permission_classes = [ApplePassPermission]
|
||||
|
||||
@method_decorator(
|
||||
condition(
|
||||
last_modified_func=lambda request, *args, **kwargs: request.auth.updated_at
|
||||
)
|
||||
)
|
||||
def get(self, request, *args, **kwargs):
|
||||
resp = ChunkBasedFileResponse(request.auth.content)
|
||||
resp["Content-Type"] = "application/vnd.apple.pkpass"
|
||||
return resp
|
||||
|
||||
|
||||
class LogView(APIView):
|
||||
authentication_classes = ()
|
||||
permission_classes = ()
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
serializer = LogEntrySerializer(data=request.data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
logger.info("Received apple wallet log messages: %s", serializer.data["logs"])
|
||||
return Response({})
|
||||
|
||||
|
||||
class DownloadPassView(EventViewMixin, OrderDetailMixin, View):
|
||||
@cached_property
|
||||
def order_position(self):
|
||||
try:
|
||||
return self.order.positions.get(pk=self.kwargs.get('position'))
|
||||
except OrderPosition.DoesNotExist:
|
||||
return None
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
if not self.order_position:
|
||||
return Http404()
|
||||
pass_obj = get_object_or_404(AppleWalletPass, order_position=self.order_position)
|
||||
resp = ChunkBasedFileResponse(pass_obj.content.file, content_type="application/vnd.apple.pkpass")
|
||||
resp['Content-Disposition'] = 'attachment; filename="{}"'.format(pass_obj.serial_number + ".pkpass").encode('ascii', 'ignore')
|
||||
return resp
|
||||
|
||||
|
||||
class DownloadCombinedPassView(EventViewMixin, OrderDetailMixin, View):
|
||||
def get(self, request, *args, **kwargs):
|
||||
pass_obj = get_object_or_404(CombinedAppleWalletPass, order=self.order)
|
||||
resp = ChunkBasedFileResponse(pass_obj.file.file, content_type="application/vnd.apple.pkpasses")
|
||||
resp['Content-Disposition'] = 'attachment; filename="{}"'.format(self.order.code + ".pkpasses").encode('ascii', 'ignore')
|
||||
return resp
|
||||
@@ -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))
|
||||
|
||||
@@ -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/>.
|
||||
#
|
||||
@@ -0,0 +1,44 @@
|
||||
#
|
||||
# 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/>.
|
||||
#
|
||||
from django.apps import AppConfig
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
from pretix import __version__ as version
|
||||
|
||||
|
||||
class WalletApp(AppConfig):
|
||||
name = "pretix.plugins.google_wallet"
|
||||
verbose_name = _("Google Wallet")
|
||||
|
||||
class PretixPluginMeta:
|
||||
name = _("Google Wallet")
|
||||
author = _("the pretix team")
|
||||
version = version
|
||||
category = "FORMAT"
|
||||
description = _(
|
||||
"Issue tickets as Google Wallet passes"
|
||||
)
|
||||
|
||||
def ready(self):
|
||||
from . import receivers # NOQA
|
||||
from . import platform # NOQA
|
||||
from . import styles # NOQA
|
||||
@@ -0,0 +1,534 @@
|
||||
import base64
|
||||
import datetime
|
||||
import enum
|
||||
import json
|
||||
import struct
|
||||
import time
|
||||
from typing import Iterable
|
||||
|
||||
import bcp47
|
||||
import requests
|
||||
from Crypto.Hash import SHA256
|
||||
from Crypto.PublicKey import ECC
|
||||
from Crypto.Signature import DSS
|
||||
from google.auth import crypt, jwt
|
||||
from google.auth.transport.requests import AuthorizedSession
|
||||
from google.oauth2 import service_account
|
||||
|
||||
from pretix.base.i18n import MaybeTranslatedString
|
||||
from pretix.base.models.orders import OrderPosition
|
||||
from pretix.helpers.i18n import localizable_to_dict
|
||||
|
||||
|
||||
class ReviewStatus(enum.StrEnum):
|
||||
APPROVED = "APPROVED"
|
||||
DRAFT = "DRAFT"
|
||||
REJECTED = "REJECTED"
|
||||
UNDER_REVIEW = "UNDER_REVIEW"
|
||||
REVIEW_STATUS_UNSPECIFIED = "REVIEW_STATUS_UNSPECIFIED"
|
||||
|
||||
|
||||
class ConfirmationCodeLabel(enum.StrEnum):
|
||||
CONFIRMATION_CODE = "CONFIRMATION_CODE"
|
||||
CONFIRMATION_NUMBER = "CONFIRMATION_NUMBER"
|
||||
ORDER_NUMBER = "ORDER_NUMBER"
|
||||
RESERVATION_NUMBER = "RESERVATION_NUMBER"
|
||||
|
||||
|
||||
class AnimationType(enum.StrEnum):
|
||||
FOIL_SHIMMER = "FOIL_SHIMMER"
|
||||
|
||||
|
||||
class DoorsOpenLabel(enum.StrEnum):
|
||||
DOORS_OPEN = "DOORS_OPEN"
|
||||
GATES_OPEN = "GATES_OPEN"
|
||||
|
||||
|
||||
class State(enum.StrEnum):
|
||||
ACTIVE = "ACTIVE"
|
||||
COMPLETED = "COMPLETED"
|
||||
EXPIRED = "EXPIRED"
|
||||
INACTIVE = "INACTIVE"
|
||||
|
||||
|
||||
class BarcodeType(enum.StrEnum):
|
||||
AZTEC = "AZTEC"
|
||||
CODE_39 = "CODE_39"
|
||||
CODE_128 = "CODE_128"
|
||||
CODABAR = "CODABAR"
|
||||
DATA_MATRIX = "DATA_MATRIX"
|
||||
EAN_8 = "EAN_8"
|
||||
EAN_13 = "EAN_13"
|
||||
EAN13 = "EAN13"
|
||||
ITF_14 = "ITF_14"
|
||||
PDF_417 = "PDF_417"
|
||||
PDF417 = "PDF417"
|
||||
QR_CODE = "QR_CODE"
|
||||
UPC_A = "UPC_A"
|
||||
TEXT_ONLY = "TEXT_ONLY"
|
||||
|
||||
|
||||
class Resource(enum.StrEnum):
|
||||
EVENT_TICKET_CLASS = "eventTicketClass"
|
||||
EVENT_TICKET_OBJECT = "eventTicketObject"
|
||||
|
||||
|
||||
def item(field):
|
||||
return {"firstValue": {"fields": [{"fieldPath": field}]}}
|
||||
|
||||
|
||||
def card_row_template_info(fields: Iterable[str]):
|
||||
items = [item(field) for field in fields]
|
||||
if len(items) == 3:
|
||||
return {
|
||||
"threeItems": {
|
||||
"startItem": items[0],
|
||||
"middleItem": items[1],
|
||||
"endItem": items[2],
|
||||
}
|
||||
}
|
||||
elif len(items) == 2:
|
||||
return {
|
||||
"twoItems": {
|
||||
"startItem": items[0],
|
||||
"endItem": items[1],
|
||||
}
|
||||
}
|
||||
else:
|
||||
return {
|
||||
"oneItem": {
|
||||
"startItem": items[0],
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def ensure_bcp47(locale: str):
|
||||
return bcp47.ParsedLanguage(locale).unparse()
|
||||
|
||||
|
||||
def localized_string(
|
||||
string: MaybeTranslatedString, locales: set[str], default_locale: str
|
||||
):
|
||||
|
||||
if isinstance(string, str):
|
||||
return {
|
||||
"defaultValue": {
|
||||
"language": ensure_bcp47(default_locale),
|
||||
"value": string,
|
||||
}
|
||||
}
|
||||
else:
|
||||
string_dict = localizable_to_dict(string, locales)
|
||||
default_string = string_dict.pop(default_locale)
|
||||
default_locale = ensure_bcp47(default_locale)
|
||||
|
||||
string_dict = {ensure_bcp47(k): v for k, v in string_dict.items()}
|
||||
|
||||
return {
|
||||
"defaultValue": {
|
||||
"language": default_locale,
|
||||
"value": default_string,
|
||||
},
|
||||
"translatedValues": [
|
||||
{"language": key, "value": value} for key, value in string_dict.items() if key != default_locale
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def localized_uri(
|
||||
uri: str, description: MaybeTranslatedString, locales: set[str], default_locale: str
|
||||
):
|
||||
return {
|
||||
"uri": uri,
|
||||
"localizedDescription": localized_string(description, locales, default_locale),
|
||||
}
|
||||
|
||||
|
||||
class Image(dict):
|
||||
def __init__(
|
||||
self,
|
||||
uri: str,
|
||||
content_description: MaybeTranslatedString,
|
||||
locales: set[str],
|
||||
default_locale: str,
|
||||
):
|
||||
self["uri"] = uri
|
||||
self["contentDescription"] = localized_string(
|
||||
content_description, locales, default_locale
|
||||
)
|
||||
|
||||
|
||||
class BaseGoogleWalletObject:
|
||||
resource: Resource
|
||||
id: str
|
||||
data: dict
|
||||
|
||||
locales: set[str]
|
||||
default_locale: str
|
||||
order_position = None
|
||||
|
||||
def _localized_string(self, string: MaybeTranslatedString):
|
||||
return localized_string(string, self.locales, self.default_locale)
|
||||
|
||||
def _localized_uri(
|
||||
self,
|
||||
uri: str,
|
||||
description: MaybeTranslatedString,
|
||||
):
|
||||
return localized_uri(uri, description, self.locales, self.default_locale)
|
||||
|
||||
def _image(self, uri: str, content_description: MaybeTranslatedString):
|
||||
return {
|
||||
"sourceUri": {"uri": uri},
|
||||
"contentDescription": self._localized_string(content_description),
|
||||
}
|
||||
|
||||
def serialize(self, mini=True):
|
||||
if mini:
|
||||
return {"id": self.id}
|
||||
else:
|
||||
return self.data
|
||||
|
||||
|
||||
class EventTicketClass(BaseGoogleWalletObject):
|
||||
resource = Resource.EVENT_TICKET_CLASS
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
issuer_name: str,
|
||||
class_id: str,
|
||||
event_name: MaybeTranslatedString,
|
||||
locales: set[str],
|
||||
default_locale: str,
|
||||
):
|
||||
self.id = class_id
|
||||
self.default_locale = default_locale
|
||||
self.locales = locales
|
||||
self.data = {
|
||||
"id": class_id,
|
||||
"issuerName": issuer_name,
|
||||
"eventName": localized_string(
|
||||
event_name, self.locales, self.default_locale
|
||||
),
|
||||
"reviewStatus": ReviewStatus.UNDER_REVIEW,
|
||||
}
|
||||
|
||||
def homepage_uri(
|
||||
self,
|
||||
uri: str,
|
||||
description: MaybeTranslatedString,
|
||||
):
|
||||
self.data["homepageUri"] = self._localized_uri(uri, description)
|
||||
|
||||
def country_code(self, code: str):
|
||||
self.data["countryCode"] = code
|
||||
|
||||
def hero_image(self, uri: str, content_description: MaybeTranslatedString):
|
||||
self.data["heroImage"] = self._image(uri, content_description)
|
||||
|
||||
def logo(self, uri: str, content_description: MaybeTranslatedString):
|
||||
self.data["logo"] = self._image(uri, content_description)
|
||||
|
||||
def wide_logo(self, uri: str, content_description: MaybeTranslatedString):
|
||||
self.data["wideLogo"] = self._image(uri, content_description)
|
||||
|
||||
def hex_background_color(self, hex_background_color: str):
|
||||
self.data["hexBackgroundColor"] = hex_background_color
|
||||
|
||||
def confirmation_code_label(self, label: ConfirmationCodeLabel):
|
||||
self.data["confirmationCodeLabel"] = label
|
||||
|
||||
def venue(self, name: MaybeTranslatedString, address: MaybeTranslatedString):
|
||||
self.data["venue"] = {
|
||||
"name": self._localized_string(name),
|
||||
"address": self._localized_string(address),
|
||||
}
|
||||
|
||||
def security_animation(self, security_animation: AnimationType):
|
||||
self.data["securityAnimation"] = {"animationType": security_animation}
|
||||
|
||||
def doors_open(
|
||||
self,
|
||||
doors_open: str,
|
||||
doors_open_label: None | DoorsOpenLabel | MaybeTranslatedString = None,
|
||||
):
|
||||
self.data.setdefault("dateTime", {})
|
||||
self.data["dateTime"]["doorsOpen"] = doors_open
|
||||
|
||||
if doors_open_label and isinstance(doors_open_label, DoorsOpenLabel):
|
||||
self.data["dateTime"]["doorsOpenLabel"] = doors_open_label
|
||||
elif doors_open_label:
|
||||
self.data["dateTime"]["customDoorsOpenLabel"] = self._localized_string(
|
||||
doors_open_label
|
||||
)
|
||||
|
||||
def start(self, start):
|
||||
self.data.setdefault("dateTime", {})
|
||||
self.data["dateTime"]["start"] = start
|
||||
|
||||
def end(self, end):
|
||||
self.data.setdefault("dateTime", {})
|
||||
self.data["dateTime"]["end"] = end
|
||||
|
||||
def callback_url(self, callback_url: str):
|
||||
self.data["callbackOptions"] = {"url": callback_url}
|
||||
|
||||
def card_template_override(self, overrides: list[list[str]]):
|
||||
self.data.setdefault("classTemplateInfo", {})
|
||||
self.data["classTemplateInfo"].setdefault("cardTemplateOverride", {})
|
||||
self.data["classTemplateInfo"]["cardTemplateOverride"][
|
||||
"cardRowTemplateInfos"
|
||||
] = [card_row_template_info(x) for x in overrides]
|
||||
|
||||
def details_item_infos(self, fields: list[str]):
|
||||
self.data.setdefault("classTemplateInfo", {})
|
||||
self.data["classTemplateInfo"].setdefault("detailsTemplateOverride", {})
|
||||
self.data["classTemplateInfo"]["detailsTemplateOverride"][
|
||||
"detailsItemInfos"
|
||||
] = [{"item": item(field)} for field in fields]
|
||||
|
||||
def add_text_module(
|
||||
self, id: str, header: MaybeTranslatedString, body: MaybeTranslatedString
|
||||
):
|
||||
self.data.setdefault("textModulesData", [])
|
||||
self.data["textModulesData"].append(
|
||||
{
|
||||
"id": id,
|
||||
"localizedHeader": self._localized_string(header),
|
||||
"localizedBody": self._localized_string(body),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class EventTicketObject(BaseGoogleWalletObject):
|
||||
resource = Resource.EVENT_TICKET_OBJECT
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
object_id: str,
|
||||
class_id: str,
|
||||
state: State,
|
||||
locales: set[str],
|
||||
default_locale: str,
|
||||
order_position: OrderPosition
|
||||
):
|
||||
self.id = object_id
|
||||
self.locales = locales
|
||||
self.default_locale = default_locale
|
||||
self.order_position = order_position
|
||||
|
||||
self.data = {
|
||||
"id": object_id,
|
||||
"classId": class_id,
|
||||
"state": state,
|
||||
}
|
||||
|
||||
def barcode(
|
||||
self,
|
||||
value: str,
|
||||
alternate_text: str | None = None,
|
||||
type: BarcodeType = BarcodeType.QR_CODE,
|
||||
):
|
||||
self.data["barcode"] = {
|
||||
"type": type,
|
||||
"value": value,
|
||||
}
|
||||
if alternate_text:
|
||||
self.data["barcode"]["alternateText"] = alternate_text
|
||||
|
||||
def reservation_info(self, confirmation_code: str):
|
||||
self.data["reservationInfo"] = {
|
||||
"confirmationCode": confirmation_code,
|
||||
}
|
||||
|
||||
def ticket_number(self, ticket_number: str):
|
||||
self.data["ticket_number"] = ticket_number
|
||||
|
||||
def valid_time_interval(self, start: datetime.datetime | None, end: datetime.datetime | None):
|
||||
self.data.setdefault("validTimeInterval", {})
|
||||
if start:
|
||||
self.data["validTimeInterval"]["start"] = {"date": start.isoformat()}
|
||||
if end:
|
||||
self.data["validTimeInterval"]["end"] = {"date": end.isoformat()}
|
||||
|
||||
def ticket_type(self, ticket_type: MaybeTranslatedString):
|
||||
self.data["ticketType"] = self._localized_string(ticket_type)
|
||||
|
||||
def ticket_holder_name(self, name):
|
||||
self.data["ticketHolderName"] = name
|
||||
|
||||
def seat(self, seat):
|
||||
self.data.setdefault("seatInfo", {})
|
||||
self.data["seatInfo"]["seat"] = self._localized_string(seat)
|
||||
|
||||
def row(self, row):
|
||||
self.data.setdefault("seatInfo", {})
|
||||
self.data["seatInfo"]["row"] = self._localized_string(row)
|
||||
|
||||
def section(self, section):
|
||||
self.data.setdefault("seatInfo", {})
|
||||
self.data["seatInfo"]["section"] = self._localized_string(section)
|
||||
|
||||
def add_text_module(
|
||||
self, id: str, header: MaybeTranslatedString, body: MaybeTranslatedString
|
||||
):
|
||||
self.data.setdefault("textModulesData", [])
|
||||
self.data["textModulesData"].append(
|
||||
{
|
||||
"id": id,
|
||||
"localizedHeader": self._localized_string(header),
|
||||
"localizedBody": self._localized_string(body),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class ButtonJWT(dict):
|
||||
def __init__(
|
||||
self,
|
||||
issuer,
|
||||
origins,
|
||||
payload: dict[str, list[BaseGoogleWalletObject]],
|
||||
precreated=True,
|
||||
):
|
||||
serialized_payload = {}
|
||||
for k, v in payload.items():
|
||||
serialized_payload[k] = [x.serialize(mini=precreated) for x in v]
|
||||
|
||||
self.payload = serialized_payload
|
||||
self.issuer = issuer
|
||||
self.origins = origins
|
||||
|
||||
def serialize(self):
|
||||
return {
|
||||
"iss": self.issuer,
|
||||
"aud": "google",
|
||||
"typ": "savetowallet",
|
||||
"iat": int(time.time()),
|
||||
"payload": self.payload,
|
||||
"origins": self.origins,
|
||||
}
|
||||
|
||||
|
||||
class Comms:
|
||||
def __init__(self, service_account_info: dict):
|
||||
credentials = service_account.Credentials.from_service_account_info(
|
||||
service_account_info,
|
||||
scopes=["https://www.googleapis.com/auth/wallet_object.issuer"],
|
||||
)
|
||||
|
||||
self._session = AuthorizedSession(credentials)
|
||||
self._signer = crypt.RSASigner.from_service_account_info(service_account_info)
|
||||
self.client_email = service_account_info.get("client_email")
|
||||
|
||||
def get_item(self, resource: Resource, resource_id: str):
|
||||
result = self._session.get(
|
||||
f"https://walletobjects.googleapis.com/walletobjects/v1/{resource}/{resource_id}"
|
||||
)
|
||||
print(result.text)
|
||||
if result.status_code == 200:
|
||||
return result.json()
|
||||
elif result.status_code == 404:
|
||||
return False
|
||||
|
||||
def put_item(self, resource: Resource, resource_id: str, payload: dict):
|
||||
item = self.get_item(resource, resource_id)
|
||||
if item is None:
|
||||
raise Exception("API Error")
|
||||
elif not item:
|
||||
result = self._session.post(
|
||||
f"https://walletobjects.googleapis.com/walletobjects/v1/{resource}?strict=true",
|
||||
json=payload,
|
||||
)
|
||||
else:
|
||||
result = self._session.put(
|
||||
f"https://walletobjects.googleapis.com/walletobjects/v1/{resource}/{resource_id}?strict=true",
|
||||
json=payload,
|
||||
)
|
||||
|
||||
print(result.json())
|
||||
result.raise_for_status()
|
||||
|
||||
return result.json()
|
||||
|
||||
def patch_item(self, resource: Resource, resource_id: str, payload: dict):
|
||||
result = self._session.patch(
|
||||
f"https://walletobjects.googleapis.com/walletobjects/v1/{resource}/{resource_id}?strict=true",
|
||||
json=payload,
|
||||
)
|
||||
|
||||
result.raise_for_status()
|
||||
|
||||
return result.json()
|
||||
|
||||
def sign_jwt(self, payload):
|
||||
return jwt.encode(self._signer, payload).decode()
|
||||
|
||||
|
||||
def pack(string):
|
||||
ret = struct.pack("<Q", len(string))[:4] + bytes(string, "utf-8")
|
||||
return ret
|
||||
|
||||
|
||||
class GooglePaySignatureManager:
|
||||
ROOT_KEYS_URL = "https://pay.google.com/gp/m/issuer/keys"
|
||||
SENDER_ID = "GooglePayPasses"
|
||||
PROTOCOL = "ECv2SigningOnly"
|
||||
|
||||
def __init__(self, recipient_id: str):
|
||||
self.recipient_id = recipient_id
|
||||
|
||||
def root_keys(self):
|
||||
r = requests.get(self.ROOT_KEYS_URL)
|
||||
r.raise_for_status()
|
||||
return r.json()["keys"]
|
||||
|
||||
def verify_signature(self, keys, salt, message, signatures):
|
||||
salt = b"".join(pack(x) for x in salt)
|
||||
for key in keys:
|
||||
if datetime.datetime.fromtimestamp(
|
||||
int(key["keyExpiration"]) / 1000, tz=datetime.UTC
|
||||
) > datetime.datetime.now(datetime.UTC):
|
||||
pk = ECC.import_key(base64.b64decode(key["keyValue"]))
|
||||
verifier = DSS.new(pk, "fips-186-3", "der")
|
||||
for signature in signatures:
|
||||
try:
|
||||
verifier.verify(
|
||||
SHA256.new(salt + pack(self.PROTOCOL) + pack(message)),
|
||||
base64.b64decode(signature),
|
||||
)
|
||||
return message
|
||||
except ValueError:
|
||||
continue
|
||||
raise ValueError("No valid signature found")
|
||||
|
||||
def unseal(self, data):
|
||||
for k in (
|
||||
"signature",
|
||||
"intermediateSigningKey",
|
||||
"protocolVersion",
|
||||
"signedMessage",
|
||||
):
|
||||
if k not in data:
|
||||
raise ValueError(f"Missing key: {k}")
|
||||
|
||||
intermediate = self.verify_signature(
|
||||
self.root_keys(),
|
||||
[self.SENDER_ID],
|
||||
data["intermediateSigningKey"]["signedKey"],
|
||||
data["intermediateSigningKey"]["signatures"],
|
||||
)
|
||||
intermediateSigningKey = json.loads(intermediate)
|
||||
message = self.verify_signature(
|
||||
[intermediateSigningKey],
|
||||
[self.SENDER_ID, self.recipient_id],
|
||||
data["signedMessage"],
|
||||
[data["signature"]],
|
||||
)
|
||||
message = json.loads(message)
|
||||
|
||||
if datetime.datetime.fromtimestamp(
|
||||
int(message["expTimeMillis"]) / 1000, tz=datetime.UTC
|
||||
) <= datetime.datetime.now(datetime.UTC):
|
||||
raise ValueError("stale event")
|
||||
|
||||
return message
|
||||
@@ -0,0 +1,53 @@
|
||||
# Generated by Django 5.2.19 on 2026-11-16 16:18
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
(
|
||||
"pretixbase",
|
||||
"0312_walletlayout",
|
||||
),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name="GoogleWalletInstance",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.BigAutoField(
|
||||
auto_created=True, primary_key=True, serialize=False
|
||||
),
|
||||
),
|
||||
("resource", models.CharField()),
|
||||
("identifier", models.CharField()),
|
||||
("data", models.JSONField()),
|
||||
("usages", models.IntegerField(default=0)),
|
||||
("updated_at", models.DateTimeField(auto_now=True)),
|
||||
(
|
||||
"event",
|
||||
models.ForeignKey(
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
to="pretixbase.event",
|
||||
),
|
||||
),
|
||||
(
|
||||
"order_position",
|
||||
models.ForeignKey(
|
||||
null=True,
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
to="pretixbase.orderposition",
|
||||
),
|
||||
),
|
||||
],
|
||||
options={
|
||||
"unique_together": {("resource", "identifier")},
|
||||
},
|
||||
),
|
||||
]
|
||||
Loaded 100 of 179 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user