Compare commits

..
Author SHA1 Message Date
Raphael Michel 04df816f4d API: Fix PATCH on item addon sets without min_count or max_count (fixes #6650) 2026-10-07 08:59:37 +02:00
Raphael Michel d291cd02e7 Docs: Fix invalid example of i18n string 2026-10-07 08:55:26 +02:00
dependabot[bot] e5dcb50229 Bump @vue/server-renderer and vue (#6646)
Bumps [@vue/server-renderer](https://github.com/vuejs/core/tree/HEAD/packages/server-renderer) to 3.5.43 and updates ancestor dependency [vue](https://github.com/vuejs/core). These dependencies need to be updated together.


Updates `@vue/server-renderer` from 3.5.30 to 3.5.43
- [Release notes](https://github.com/vuejs/core/releases)
- [Changelog](https://github.com/vuejs/core/blob/main/CHANGELOG.md)
- [Commits](https://github.com/vuejs/core/commits/v3.5.43/packages/server-renderer)

Updates `vue` from 3.5.30 to 3.5.43
- [Release notes](https://github.com/vuejs/core/releases)
- [Changelog](https://github.com/vuejs/core/blob/main/CHANGELOG.md)
- [Commits](https://github.com/vuejs/core/compare/v3.5.30...v3.5.43)

---
updated-dependencies:
- dependency-name: "@vue/server-renderer"
  dependency-version: 3.5.43
  dependency-type: indirect
- dependency-name: vue
  dependency-version: 3.5.43
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-07 08:54:01 +02:00
dependabot[bot] 9d333bc2cf Update cryptography requirement from >=50.0.1 to >=50.0.2 (#6648)
Updates the requirements on [cryptography](https://github.com/pyca/cryptography) to permit the latest version.
- [Changelog](https://github.com/pyca/cryptography/blob/main/CHANGELOG.rst)
- [Commits](https://github.com/pyca/cryptography/compare/50.0.1...50.0.2)

---
updated-dependencies:
- dependency-name: cryptography
  dependency-version: 50.0.2
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-06 22:33:33 +02:00
dependabot[bot] 45038d07f3 Bump django-filter from 26.1 to 26.2 (#6647)
Bumps [django-filter](https://github.com/carltongibson/django-filter) from 26.1 to 26.2.
- [Release notes](https://github.com/carltongibson/django-filter/releases)
- [Changelog](https://github.com/carltongibson/django-filter/blob/main/CHANGES.rst)
- [Commits](https://github.com/carltongibson/django-filter/compare/26.1...26.2)

---
updated-dependencies:
- dependency-name: django-filter
  dependency-version: '26.2'
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-06 22:33:30 +02:00
dependabot[bot] 00f0dfec88 Bump postcss-selector-parser from 7.1.5 to 7.1.6 (#6644)
Bumps [postcss-selector-parser](https://github.com/postcss/postcss-selector-parser) from 7.1.5 to 7.1.6.
- [Release notes](https://github.com/postcss/postcss-selector-parser/releases)
- [Changelog](https://github.com/postcss/postcss-selector-parser/blob/main/CHANGELOG.md)
- [Commits](https://github.com/postcss/postcss-selector-parser/compare/7.1.5...7.1.6)

---
updated-dependencies:
- dependency-name: postcss-selector-parser
  dependency-version: 7.1.6
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-06 22:30:52 +02:00
dependabot[bot] 1975a9d891 Bump source-map-js from 1.2.1 to 1.2.2 (#6645)
Bumps [source-map-js](https://github.com/7rulnik/source-map-js) from 1.2.1 to 1.2.2.
- [Release notes](https://github.com/7rulnik/source-map-js/releases)
- [Changelog](https://github.com/7rulnik/source-map-js/blob/main/CHANGELOG.md)
- [Commits](https://github.com/7rulnik/source-map-js/compare/v1.2.1...v1.2.2)

---
updated-dependencies:
- dependency-name: source-map-js
  dependency-version: 1.2.2
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-06 22:30:42 +02:00
dependabot[bot] 02b9b6941d Bump smol-toml from 1.7.1 to 1.9.0 (#6643)
Bumps [smol-toml](https://github.com/squirrelchat/smol-toml) from 1.7.1 to 1.9.0.
- [Release notes](https://github.com/squirrelchat/smol-toml/releases)
- [Commits](https://github.com/squirrelchat/smol-toml/compare/v1.7.1...v1.9.0)

---
updated-dependencies:
- dependency-name: smol-toml
  dependency-version: 1.9.0
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-06 22:30:34 +02:00
dependabot[bot] da2ac6c386 Update tlds requirement from >=2026072401 to >=2026093003 (#6642)
Updates the requirements on [tlds](https://github.com/kichik/tlds) to permit the latest version.
- [Commits](https://github.com/kichik/tlds/commits)

---
updated-dependencies:
- dependency-name: tlds
  dependency-version: '2026093003'
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-06 11:39:19 +02:00
Hijiri Umemoto b9fbe699ab Translations: Update Japanese
Currently translated at 100.0% (6442 of 6442 strings)

Translation: pretix/pretix
Translate-URL: https://translate.pretix.eu/projects/pretix/pretix/ja/

powered by weblate
2026-10-06 11:04:53 +02:00
Oksigenia 8e3f3cc8c8 Translations: Update Spanish
Currently translated at 100.0% (260 of 260 strings)

Translation: pretix/pretix (JavaScript parts)
Translate-URL: https://translate.pretix.eu/projects/pretix/pretix-js/es/

powered by weblate
2026-10-06 11:04:53 +02:00
Oksigenia 945f80b288 Translations: Update Spanish
Currently translated at 100.0% (6442 of 6442 strings)

Translation: pretix/pretix
Translate-URL: https://translate.pretix.eu/projects/pretix/pretix/es/

powered by weblate
2026-10-06 11:04:53 +02:00
Translate pretix user 594 25799da70d Translations: Update Russian
Currently translated at 25.9% (1672 of 6442 strings)

Translation: pretix/pretix
Translate-URL: https://translate.pretix.eu/projects/pretix/pretix/ru/

powered by weblate
2026-10-06 11:04:53 +02:00
Nate Horst 6b01023d16 Translations: Update Thai
Currently translated at 100.0% (260 of 260 strings)

Translation: pretix/pretix (JavaScript parts)
Translate-URL: https://translate.pretix.eu/projects/pretix/pretix-js/th/

powered by weblate
2026-10-06 11:04:53 +02:00
Nate Horst 98644db976 Translations: Update Thai
Currently translated at 100.0% (6442 of 6442 strings)

Translation: pretix/pretix
Translate-URL: https://translate.pretix.eu/projects/pretix/pretix/th/

powered by weblate
2026-10-06 11:04:53 +02:00
Translate pretix user 594 814ae7f4d9 Translations: Update Russian
Currently translated at 44.6% (116 of 260 strings)

Translation: pretix/pretix (JavaScript parts)
Translate-URL: https://translate.pretix.eu/projects/pretix/pretix-js/ru/

powered by weblate
2026-10-06 11:04:53 +02:00
Translate pretix user 594 ae39a1e112 Translations: Update Russian
Currently translated at 25.9% (1670 of 6442 strings)

Translation: pretix/pretix
Translate-URL: https://translate.pretix.eu/projects/pretix/pretix/ru/

powered by weblate
2026-10-06 11:04:53 +02:00
Translate pretix user 594 61b94f1128 Translations: Update Russian
Currently translated at 41.9% (109 of 260 strings)

Translation: pretix/pretix (JavaScript parts)
Translate-URL: https://translate.pretix.eu/projects/pretix/pretix-js/ru/

powered by weblate
2026-10-06 11:04:53 +02:00
Translate pretix user 594 dbb586ad5a Translations: Update Russian
Currently translated at 24.3% (1569 of 6442 strings)

Translation: pretix/pretix
Translate-URL: https://translate.pretix.eu/projects/pretix/pretix/ru/

powered by weblate
2026-10-06 11:04:53 +02:00
Nate Horst 295b0443fb Translations: Update Thai
Currently translated at 99.9% (6441 of 6442 strings)

Translation: pretix/pretix
Translate-URL: https://translate.pretix.eu/projects/pretix/pretix/th/

powered by weblate
2026-10-06 11:04:53 +02:00
Nate Horst 31031225d3 Translations: Update Thai
Currently translated at 97.7% (6299 of 6442 strings)

Translation: pretix/pretix
Translate-URL: https://translate.pretix.eu/projects/pretix/pretix/th/

powered by weblate
2026-10-06 11:04:53 +02:00
Nate Horst d600115ea5 Translations: Update Thai
Currently translated at 95.2% (6134 of 6442 strings)

Translation: pretix/pretix
Translate-URL: https://translate.pretix.eu/projects/pretix/pretix/th/

powered by weblate
2026-10-06 11:04:53 +02:00
CVZ-es 3d9ebb3072 Translations: Update Spanish
Currently translated at 100.0% (6442 of 6442 strings)

Translation: pretix/pretix
Translate-URL: https://translate.pretix.eu/projects/pretix/pretix/es/

powered by weblate
2026-10-06 11:04:53 +02:00
CVZ-es c9667e77c3 Translations: Update French
Currently translated at 100.0% (6442 of 6442 strings)

Translation: pretix/pretix
Translate-URL: https://translate.pretix.eu/projects/pretix/pretix/fr/

powered by weblate
2026-10-06 11:04:53 +02:00
Nate Horst b2b797f4d3 Translations: Update Thai
Currently translated at 83.2% (5366 of 6442 strings)

Translation: pretix/pretix
Translate-URL: https://translate.pretix.eu/projects/pretix/pretix/th/

powered by weblate
2026-10-06 11:04:53 +02:00
Nate Horst 693adbc727 Translations: Update Thai
Currently translated at 81.3% (5242 of 6442 strings)

Translation: pretix/pretix
Translate-URL: https://translate.pretix.eu/projects/pretix/pretix/th/

powered by weblate
2026-10-06 11:04:53 +02:00
szurofkamarciidfbe08444ef04788 8d9840be8d Translations: Update Hungarian
Currently translated at 98.7% (6364 of 6442 strings)

Translation: pretix/pretix
Translate-URL: https://translate.pretix.eu/projects/pretix/pretix/hu/

powered by weblate
2026-10-06 11:04:53 +02:00
Raphael Michel 73c0c61b6d Translations: Update Swedish
Currently translated at 98.4% (256 of 260 strings)

Translation: pretix/pretix (JavaScript parts)
Translate-URL: https://translate.pretix.eu/projects/pretix/pretix-js/sv/

powered by weblate
2026-10-06 11:04:53 +02:00
Raphael Michel a813269d1f Translations: Update Swedish
Currently translated at 85.4% (5503 of 6442 strings)

Translation: pretix/pretix
Translate-URL: https://translate.pretix.eu/projects/pretix/pretix/sv/

powered by weblate
2026-10-06 11:04:53 +02:00
Translate pretix user 594 d6bc1fa977 Translations: Update Russian
Currently translated at 38.8% (101 of 260 strings)

Translation: pretix/pretix (JavaScript parts)
Translate-URL: https://translate.pretix.eu/projects/pretix/pretix-js/ru/

powered by weblate
2026-10-06 11:04:53 +02:00
Translate pretix user 594 249edfa2c4 Translations: Update Russian
Currently translated at 20.5% (1322 of 6442 strings)

Translation: pretix/pretix
Translate-URL: https://translate.pretix.eu/projects/pretix/pretix/ru/

powered by weblate
2026-10-06 11:04:53 +02:00
dependabot[bot] 0c28151d30 Update sentry-sdk requirement from ==2.70.* to ==2.71.* (#6632)
Updates the requirements on [sentry-sdk](https://github.com/getsentry/sentry-python) to permit the latest version.
- [Release notes](https://github.com/getsentry/sentry-python/releases)
- [Changelog](https://github.com/getsentry/sentry-python/blob/master/CHANGELOG.md)
- [Commits](https://github.com/getsentry/sentry-python/compare/2.70.0...2.71.0)

---
updated-dependencies:
- dependency-name: sentry-sdk
  dependency-version: 2.71.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-06 10:59:40 +02:00
pajowu 5bb3b7e35e Fix help_text showing as 'None' in orderimport&permissions (#6631) 2026-10-06 10:12:27 +02:00
Richard Schreiber 4119d04fba Add border to and increase text-contrast on disabled button (#6622)
* Add border to and increase text-contrast on disabled button

* Do not add border to disabled btn-link

* Add background to disabled button to further distinguish
2026-10-02 09:15:05 +02:00
84858bc048 Allow mails to be sent to addon-attendees (Z#23213551) (#6235)
Remove restrictions that prevent mails to be sent to addon-product-attendees while reducing amount of mails sent to the same email-addresses

Co-authored-by: Richard Schreiber <schreiber@rami.io>
Co-authored-by: Kara Engelhardt <engelhardt@pretix.eu>
2026-10-01 13:13:55 +02:00
Raphael Michel e8c091741b Invoice export: Fix crash PRETIXEU-FGE 2026-10-01 11:43:36 +02:00
Richard Schreiber ebdfd21b0f Fix JavaScript error description passing HTML (#6630) 2026-10-01 11:28:36 +02:00
pajowuandRichard Schreiber ed0b3cab7f Fix addon legend overlapping with profile checkbox (Z#23247075) (#6568)
* Fix addon legend overlapping with profile checkbox (Z#23247075)

* Update src/pretix/static/pretixpresale/scss/_checkout.scss

Co-authored-by: Richard Schreiber <schreiber@pretix.eu>

---------

Co-authored-by: Richard Schreiber <schreiber@pretix.eu>
2026-10-01 09:49:23 +02:00
167 changed files with 5526 additions and 9419 deletions

No files matched your search

+1 -1
View File
@@ -173,7 +173,7 @@ Datetime String in ISO 8601 format ``"2017-12-27T10:00:00Z"``
with timezone (normally UTC) ``"2017-12-27T10:00:00.596934Z"``,
``"2017-12-27T10:00:00+02:00"``
Date String in ISO 8601 format ``2017-12-27``
Multi-lingual string Object of strings ``{"en": "red", "de": "rot", "de_Informal": "rot"}``
Multi-lingual string Object of strings ``{"en": "red", "de": "rot", "de-informal": "rot"}``
Money String with decimal number ``"23.42"``
Currency String with ISO 4217 code ``"EUR"``, ``"USD"``
Relative datetime *either* String in ISO 8601 ``"2017-12-27T10:00:00.596934Z"``,
+2
View File
@@ -43,6 +43,8 @@ const ignores = globalIgnores([
'src/pretix/static/pretixbase/js/addressform.js',
'src/pretix/static/pretixbase/js/asynctask.js',
'src/pretix/static/pretixbase/js/details.js',
'src/pretix/static/pretixbase/js/gettextstub.js',
'src/pretix/static/pretixbase/js/i18nstring.js',
'src/pretix/static/pretixcontrol/js/menu.js',
'src/pretix/static/pretixcontrol/js/ui/editor.js',
'src/pretix/static/pretixcontrol/js/ui/geo.js',
+92 -104
View File
@@ -9,8 +9,7 @@
"version": "1.0.0",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"vue": "^3.5.30",
"vue-slicksort": "^2.0.5"
"vue": "^3.5.30"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
@@ -41,30 +40,30 @@
"license": "MIT"
},
"node_modules/@babel/helper-string-parser": {
"version": "7.27.1",
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz",
"integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==",
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz",
"integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==",
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/helper-validator-identifier": {
"version": "7.28.5",
"resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz",
"integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==",
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",
"integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/parser": {
"version": "7.29.0",
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.0.tgz",
"integrity": "sha512-IyDgFV5GeDUVX4YdF/3CPULtVGSXXMLh1xVIgdCgxApktqnQV0r7/8Nqthg+8YLGaAtdyIlo2qIdZrbCv4+7ww==",
"version": "7.29.9",
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.9.tgz",
"integrity": "sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==",
"license": "MIT",
"dependencies": {
"@babel/types": "^7.29.0"
"@babel/types": "^7.29.8"
},
"bin": {
"parser": "bin/babel-parser.js"
@@ -74,13 +73,13 @@
}
},
"node_modules/@babel/types": {
"version": "7.29.0",
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz",
"integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==",
"version": "7.29.8",
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz",
"integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==",
"license": "MIT",
"dependencies": {
"@babel/helper-string-parser": "^7.27.1",
"@babel/helper-validator-identifier": "^7.28.5"
"@babel/helper-string-parser": "^7.29.7",
"@babel/helper-validator-identifier": "^7.29.7"
},
"engines": {
"node": ">=6.9.0"
@@ -379,9 +378,9 @@
}
},
"node_modules/@jridgewell/sourcemap-codec": {
"version": "1.5.5",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
"integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
"integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
"license": "MIT"
},
"node_modules/@napi-rs/wasm-runtime": {
@@ -1448,53 +1447,53 @@
"license": "MIT"
},
"node_modules/@vue/compiler-core": {
"version": "3.5.30",
"resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.5.30.tgz",
"integrity": "sha512-s3DfdZkcu/qExZ+td75015ljzHc6vE+30cFMGRPROYjqkroYI5NV2X1yAMX9UeyBNWB9MxCfPcsjpLS11nzkkw==",
"version": "3.5.43",
"resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.5.43.tgz",
"integrity": "sha512-zdiLhnbe1QQqgDT8xZMpNmyqZ3qlI+/Q/FHQco57Kwl/b05HhCzN6eVGN9QU9rbga4CrS0H5SYY8VGHZCt/1Hg==",
"license": "MIT",
"dependencies": {
"@babel/parser": "^7.29.0",
"@vue/shared": "3.5.30",
"@babel/parser": "^7.29.8",
"@vue/shared": "3.5.43",
"entities": "^7.0.1",
"estree-walker": "^2.0.2",
"source-map-js": "^1.2.1"
}
},
"node_modules/@vue/compiler-dom": {
"version": "3.5.30",
"resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.5.30.tgz",
"integrity": "sha512-eCFYESUEVYHhiMuK4SQTldO3RYxyMR/UQL4KdGD1Yrkfdx4m/HYuZ9jSfPdA+nWJY34VWndiYdW/wZXyiPEB9g==",
"version": "3.5.43",
"resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.5.43.tgz",
"integrity": "sha512-PEZoAk3NQmsn/ejMzSOCyTYqwGqczrWm70PuhBKjjv1+TCoQAaO/zOqNwjV+honlNstT5ILxtc+8r8UUfj+iEQ==",
"license": "MIT",
"dependencies": {
"@vue/compiler-core": "3.5.30",
"@vue/shared": "3.5.30"
"@vue/compiler-core": "3.5.43",
"@vue/shared": "3.5.43"
}
},
"node_modules/@vue/compiler-sfc": {
"version": "3.5.30",
"resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.5.30.tgz",
"integrity": "sha512-LqmFPDn89dtU9vI3wHJnwaV6GfTRD87AjWpTWpyrdVOObVtjIuSeZr181z5C4PmVx/V3j2p+0f7edFKGRMpQ5A==",
"version": "3.5.43",
"resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.5.43.tgz",
"integrity": "sha512-FCbrG3XNCRl+js3huuKx4IVHBLTvMkJhVepjbxSPu1gn4yWLaYtGNQdjJGZaMytXB6qb76qQDDmDSLy/vkmleQ==",
"license": "MIT",
"dependencies": {
"@babel/parser": "^7.29.0",
"@vue/compiler-core": "3.5.30",
"@vue/compiler-dom": "3.5.30",
"@vue/compiler-ssr": "3.5.30",
"@vue/shared": "3.5.30",
"@babel/parser": "^7.29.8",
"@vue/compiler-core": "3.5.43",
"@vue/compiler-dom": "3.5.43",
"@vue/compiler-ssr": "3.5.43",
"@vue/shared": "3.5.43",
"estree-walker": "^2.0.2",
"magic-string": "^0.30.21",
"postcss": "^8.5.8",
"postcss": "^8.5.28",
"source-map-js": "^1.2.1"
}
},
"node_modules/@vue/compiler-ssr": {
"version": "3.5.30",
"resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.5.30.tgz",
"integrity": "sha512-NsYK6OMTnx109PSL2IAyf62JP6EUdk4Dmj6AkWcJGBvN0dQoMYtVekAmdqgTtWQgEJo+Okstbf/1p7qZr5H+bA==",
"version": "3.5.43",
"resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.5.43.tgz",
"integrity": "sha512-GF62orf7KiJX9RqrHNGrYBudsQGD0OhJ5nDs90O8UiDuS40+YMYomiXu6w6EuvtXuRDc3MSNis3EaaSKAVSWpg==",
"license": "MIT",
"dependencies": {
"@vue/compiler-dom": "3.5.30",
"@vue/shared": "3.5.30"
"@vue/compiler-dom": "3.5.43",
"@vue/shared": "3.5.43"
}
},
"node_modules/@vue/eslint-config-typescript": {
@@ -1538,53 +1537,51 @@
}
},
"node_modules/@vue/reactivity": {
"version": "3.5.30",
"resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.30.tgz",
"integrity": "sha512-179YNgKATuwj9gB+66snskRDOitDiuOZqkYia7mHKJaidOMo/WJxHKF8DuGc4V4XbYTJANlfEKb0yxTQotnx4Q==",
"version": "3.5.43",
"resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.43.tgz",
"integrity": "sha512-G/c9GyOZNI2jVaaS6OX1EF1SSFSv7H0ERqNTl4+DTFMlZmB5eVAB53aLQNam/7NL2NPtaDD7RdVrzf8uJzMuOA==",
"license": "MIT",
"dependencies": {
"@vue/shared": "3.5.30"
"@vue/shared": "3.5.43"
}
},
"node_modules/@vue/runtime-core": {
"version": "3.5.30",
"resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.5.30.tgz",
"integrity": "sha512-e0Z+8PQsUTdwV8TtEsLzUM7SzC7lQwYKePydb7K2ZnmS6jjND+WJXkmmfh/swYzRyfP1EY3fpdesyYoymCzYfg==",
"version": "3.5.43",
"resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.5.43.tgz",
"integrity": "sha512-hU6U6VnVhBGQDpvlnnDlIB8ZGJBiOcgk2lh/0InltHiz3D8oSkluvuvY+do1G2H3+udeKFsmaBlgVYP7gXQzEw==",
"license": "MIT",
"dependencies": {
"@vue/reactivity": "3.5.30",
"@vue/shared": "3.5.30"
"@vue/reactivity": "3.5.43",
"@vue/shared": "3.5.43"
}
},
"node_modules/@vue/runtime-dom": {
"version": "3.5.30",
"resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.5.30.tgz",
"integrity": "sha512-2UIGakjU4WSQ0T4iwDEW0W7vQj6n7AFn7taqZ9Cvm0Q/RA2FFOziLESrDL4GmtI1wV3jXg5nMoJSYO66egDUBw==",
"version": "3.5.43",
"resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.5.43.tgz",
"integrity": "sha512-Bb2Jc0YjjJdMt1SJmb9b2L/IWd3I8lIT9x9eS/xvvP9CiVgna0ffua74xKRmt4/uSJ+0r4iN8ex1jrqkhQGWQw==",
"license": "MIT",
"dependencies": {
"@vue/reactivity": "3.5.30",
"@vue/runtime-core": "3.5.30",
"@vue/shared": "3.5.30",
"@vue/reactivity": "3.5.43",
"@vue/runtime-core": "3.5.43",
"@vue/shared": "3.5.43",
"csstype": "^3.2.3"
}
},
"node_modules/@vue/server-renderer": {
"version": "3.5.30",
"resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.5.30.tgz",
"integrity": "sha512-v+R34icapydRwbZRD0sXwtHqrQJv38JuMB4JxbOxd8NEpGLny7cncMp53W9UH/zo4j8eDHjQ1dEJXwzFQknjtQ==",
"version": "3.5.43",
"resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.5.43.tgz",
"integrity": "sha512-l2Ygjv9NehV94PSBxNWsAHC0j/eIIKbn92mBuWXAPGLnn6HfJ6MH5ubsd+Nk0YoZ5FRuxWI1P2VSoh+dbPQhCQ==",
"license": "MIT",
"dependencies": {
"@vue/compiler-ssr": "3.5.30",
"@vue/shared": "3.5.30"
},
"peerDependencies": {
"vue": "3.5.30"
"@vue/compiler-ssr": "3.5.43",
"@vue/runtime-dom": "3.5.43",
"@vue/shared": "3.5.43"
}
},
"node_modules/@vue/shared": {
"version": "3.5.30",
"resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.5.30.tgz",
"integrity": "sha512-YXgQ7JjaO18NeK2K9VTbDHaFy62WrObMa6XERNfNOkAhD1F1oDSf3ZJ7K6GqabZ0BvSDHajp8qfS5Sa2I9n8uQ==",
"version": "3.5.43",
"resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.5.43.tgz",
"integrity": "sha512-uksS7YGMR5NZyr4JNq0Rp+QyLns0ueaz20KwzIPW9R0LH1Vnt4E+XUM29PNseEbf1www2gOuhuDi5AKOIXag9Q==",
"license": "MIT"
},
"node_modules/acorn": {
@@ -3191,9 +3188,9 @@
"license": "MIT"
},
"node_modules/nanoid": {
"version": "3.3.16",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz",
"integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==",
"version": "3.3.20",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz",
"integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==",
"funding": [
{
"type": "github",
@@ -3367,9 +3364,9 @@
}
},
"node_modules/postcss": {
"version": "8.5.23",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.23.tgz",
"integrity": "sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg==",
"version": "8.5.29",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.29.tgz",
"integrity": "sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ==",
"funding": [
{
"type": "opencollective",
@@ -3386,18 +3383,18 @@
],
"license": "MIT",
"dependencies": {
"nanoid": "^3.3.16",
"nanoid": "^3.3.19",
"picocolors": "^1.1.1",
"source-map-js": "^1.2.1"
"source-map-js": "^1.2.2"
},
"engines": {
"node": "^10 || ^12 || >=14"
}
},
"node_modules/postcss-selector-parser": {
"version": "7.1.5",
"resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.5.tgz",
"integrity": "sha512-KvvtD7SrlBP7dlgkBghEE3r84CABm5SmV2aNcG4oCA+qDnJ/tvKonFVvwWAyyWUEwxuNawdfEAZKP9zM3oZ2Uw==",
"version": "7.1.6",
"resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.6.tgz",
"integrity": "sha512-7qASPzhKF2l2KLboRZux8CCTRMdGiV08vWmyKzPz22qZ7ZjQBOeY7rNzNoCLSUiftJ7HUq0GERHmxw/t0dCdMw==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -4163,9 +4160,9 @@
}
},
"node_modules/smol-toml": {
"version": "1.7.1",
"resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.7.1.tgz",
"integrity": "sha512-PPlsspAZ4jbMBu5DMFhfUGDQLu/vrL4SyBROVS37x8ynnVmFIs1VPBz1Co8Xks3TvpIaZXmU85y4DrQ+UyVFoQ==",
"version": "1.9.0",
"resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.9.0.tgz",
"integrity": "sha512-hpd+HLON7HdZXqYchMM/+LaTTbdK0AU3NngIJ4KVyWbY9bfQqdL9cD+4yf6dUoU2Ap4VsU0JkQi6FxAI1B2mXQ==",
"dev": true,
"license": "BSD-3-Clause",
"engines": {
@@ -4186,9 +4183,9 @@
}
},
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
"integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",
"integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.10.0"
@@ -4593,16 +4590,16 @@
"license": "MIT"
},
"node_modules/vue": {
"version": "3.5.30",
"resolved": "https://registry.npmjs.org/vue/-/vue-3.5.30.tgz",
"integrity": "sha512-hTHLc6VNZyzzEH/l7PFGjpcTvUgiaPK5mdLkbjrTeWSRcEfxFrv56g/XckIYlE9ckuobsdwqd5mk2g1sBkMewg==",
"version": "3.5.43",
"resolved": "https://registry.npmjs.org/vue/-/vue-3.5.43.tgz",
"integrity": "sha512-o5qZoksdnjIKvW1srZ3ab7pcDNYAerBjRe54D0LBLfRdCYFrSgBHVXokMas35czQc0//lmx4/tuY4ZNQ+Rf2Ng==",
"license": "MIT",
"dependencies": {
"@vue/compiler-dom": "3.5.30",
"@vue/compiler-sfc": "3.5.30",
"@vue/runtime-dom": "3.5.30",
"@vue/server-renderer": "3.5.30",
"@vue/shared": "3.5.30"
"@vue/compiler-dom": "3.5.43",
"@vue/compiler-sfc": "3.5.43",
"@vue/runtime-dom": "3.5.43",
"@vue/server-renderer": "3.5.43",
"@vue/shared": "3.5.43"
},
"peerDependencies": {
"typescript": "*"
@@ -4650,15 +4647,6 @@
"vue-eslint-parser": "^10.0.0"
}
},
"node_modules/vue-slicksort": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/vue-slicksort/-/vue-slicksort-2.0.5.tgz",
"integrity": "sha512-fXz1YrNjhUbJK7o0tMk27mIr4pMAZYLSYvtmLazCtfpvz+zafPCn34ILDL8B7hT7WLVZKreYs6JVe5VWymqmzA==",
"license": "MIT",
"peerDependencies": {
"vue": ">=3.0.0"
}
},
"node_modules/which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
+1 -2
View File
@@ -27,8 +27,7 @@
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"vue": "^3.5.30",
"vue-slicksort": "^2.0.5"
"vue": "^3.5.30"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
+4 -4
View File
@@ -33,7 +33,7 @@ dependencies = [
"bleach==6.4.*",
"celery==5.6.*",
"chardet==5.2.*",
"cryptography>=50.0.1",
"cryptography>=50.0.2",
"css-inline==0.21.*",
"defusedcsv>=3.0.0",
"dnspython==2.*",
@@ -41,7 +41,7 @@ dependencies = [
"django-bootstrap3==26.2",
"django-compressor==4.6.0",
"django-countries==9.1.*",
"django-filter==26.1",
"django-filter==26.2",
"django-formset-js-improved==0.5.0.5",
"django-formtools==2.7",
"django-hierarkey==2.0.*,>=2.0.2",
@@ -94,11 +94,11 @@ dependencies = [
"redis==7.4.*",
"reportlab==5.0.*",
"requests==2.34.*",
"sentry-sdk==2.70.*",
"sentry-sdk==2.71.*",
"sepaxml==2.7.*",
"stripe==7.9.*",
"text-unidecode==1.*",
"tlds>=2026072401",
"tlds>=2026093003",
"tqdm==4.*",
"ua-parser==1.0.*",
"vobject==0.9.*",
-12
View File
@@ -100,10 +100,6 @@ class PretixScanSecurityProfile(AllowListSecurityProfile):
('GET', 'api-v1:itemcategory-list'),
('GET', 'api-v1:item-list'),
('GET', 'api-v1:question-list'),
('GET', 'api-v1:compatquestion-list'),
('GET', 'api-v1:datafield-list'),
('GET', 'api-v1:questionnaire-list'),
('GET', 'api-v1:questionnairechild-list'),
('GET', 'api-v1:badgelayout-list'),
('GET', 'api-v1:badgeitem-list'),
('GET', 'api-v1:checkinlist-list'),
@@ -145,10 +141,6 @@ class PretixScanNoSyncNoSearchSecurityProfile(AllowListSecurityProfile):
('GET', 'api-v1:itemcategory-list'),
('GET', 'api-v1:item-list'),
('GET', 'api-v1:question-list'),
('GET', 'api-v1:compatquestion-list'),
('GET', 'api-v1:datafield-list'),
('GET', 'api-v1:questionnaire-list'),
('GET', 'api-v1:questionnairechild-list'),
('GET', 'api-v1:badgelayout-list'),
('GET', 'api-v1:badgeitem-list'),
('GET', 'api-v1:checkinlist-list'),
@@ -185,10 +177,6 @@ class PretixScanNoSyncSecurityProfile(AllowListSecurityProfile):
('GET', 'api-v1:itemcategory-list'),
('GET', 'api-v1:item-list'),
('GET', 'api-v1:question-list'),
('GET', 'api-v1:compatquestion-list'),
('GET', 'api-v1:datafield-list'),
('GET', 'api-v1:questionnaire-list'),
('GET', 'api-v1:questionnairechild-list'),
('GET', 'api-v1:badgelayout-list'),
('GET', 'api-v1:badgeitem-list'),
('GET', 'api-v1:checkinlist-list'),
-99
View File
@@ -1,99 +0,0 @@
#
# This file is part of pretix (Community Edition).
#
# Copyright (C) 2014-2020 Raphael Michel and contributors
# Copyright (C) 2020-today pretix GmbH and contributors
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
# Public License as published by the Free Software Foundation in version 3 of the License.
#
# ADDITIONAL TERMS APPLY: Pursuant to Section 7 of the GNU Affero General Public License, additional terms are
# applicable granting you additional permissions and placing additional restrictions on your usage of this software.
# Please refer to the pretix LICENSE file to obtain the full terms applicable to this work. If you did not receive
# this file, see <https://pretix.eu/about/en/license>.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along with this program. If not, see
# <https://www.gnu.org/licenses/>.
#
from functools import reduce
from rest_framework import serializers
from pretix.api.exceptions import CompatException
class MergeField(serializers.Field):
"""
Read-only field that iterates over a list of related objects, picks a value from each, and merges the values
in a configurable way (mode parameter).
:param mode: list: returns a list of all picked values
consensus: returns the value only if it is equal on all related objects, otherwise
raises or returns an error object
union: only supported if picked values are iterables - generates union of all sub-items
bool_or: returns a boolean that is true if at least one picked value is truthy
"""
def __init__(self, related_name, inner_field, mode, **kwargs):
self.inner_field = inner_field
self.related_name = related_name
self.merge_mode = mode
assert mode in ('list', 'consensus', 'union', 'bool_or',)
kwargs['source'] = '*'
kwargs['read_only'] = True
super().__init__(**kwargs)
def bind(self, field_name, parent):
self.field_name = field_name
self.parent = parent
self.inner_field.bind(field_name, parent)
def get_attribute(self, instance):
vals = []
for ref in getattr(instance, self.related_name).all():
val = self.inner_field.get_attribute(ref)
if val is not None:
val = self.inner_field.to_representation(val)
vals.append(val)
if self.merge_mode == 'list':
return vals
elif self.merge_mode == 'consensus':
if len(vals) >= 1 and all(val == vals[0] for val in vals):
return vals[0]
else:
errmes = 'Questionnaire configuration incompatible with old data model due to conflicting values of ' + self.field_name
if self.context['ignore_errors']:
return {'_error': errmes, '_values': vals}
else:
raise CompatException({'detail': errmes, '_values': vals})
elif self.merge_mode == 'union':
return sorted(set(sum(vals, [])))
elif self.merge_mode == 'bool_or':
return reduce(lambda a, b: a or bool(b), vals, False)
else:
raise Exception('Unknown merge mode: ' + self.merge_mode)
def to_representation(self, value):
return value
def get_partial_validation_result(data, serializer_class, prepare_data=None, **serializer_kwargs):
errors = []
serializer = serializer_class(data=prepare_data(data) if prepare_data else data, **serializer_kwargs)
if not serializer.is_valid():
if isinstance(serializer.errors, list):
valid_inputs = []
for input, error in zip(data, serializer.errors):
if error:
errors.append((input, error))
else:
valid_inputs.append(input)
print(valid_inputs)
print('errors', errors)
serializer.initial_data = prepare_data(valid_inputs) if prepare_data else valid_inputs
del serializer._validated_data
serializer.is_valid(raise_exception=True)
return serializer.validated_data, errors
-28
View File
@@ -1,28 +0,0 @@
#
# This file is part of pretix (Community Edition).
#
# Copyright (C) 2014-2020 Raphael Michel and contributors
# Copyright (C) 2020-today pretix GmbH and contributors
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
# Public License as published by the Free Software Foundation in version 3 of the License.
#
# ADDITIONAL TERMS APPLY: Pursuant to Section 7 of the GNU Affero General Public License, additional terms are
# applicable granting you additional permissions and placing additional restrictions on your usage of this software.
# Please refer to the pretix LICENSE file to obtain the full terms applicable to this work. If you did not receive
# this file, see <https://pretix.eu/about/en/license>.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along with this program. If not, see
# <https://www.gnu.org/licenses/>.
#
from rest_framework.exceptions import APIException
class CompatException(APIException):
status = 410
default_code = 'incompatible_data'
+14 -4
View File
@@ -32,7 +32,6 @@ from rest_framework.exceptions import ValidationError
from pretix.api.serializers.i18n import I18nAwareModelSerializer
from pretix.api.serializers.order import (
AnswerCreateSerializer, AnswerSerializer, InlineSeatSerializer,
MixedAnswerListSerializer,
)
from pretix.base.models import SalesChannel, Seat, Voucher
from pretix.base.models.orders import CartPosition
@@ -44,7 +43,7 @@ class TaxIncludedField(serializers.Field):
class CartPositionSerializer(I18nAwareModelSerializer):
answers = MixedAnswerListSerializer(child=AnswerSerializer(), source='*')
answers = AnswerSerializer(many=True)
seat = InlineSeatSerializer()
includes_tax = TaxIncludedField(source='*')
@@ -56,7 +55,7 @@ class CartPositionSerializer(I18nAwareModelSerializer):
class BaseCartPositionCreateSerializer(I18nAwareModelSerializer):
answers = MixedAnswerListSerializer(child=AnswerCreateSerializer(required=False), source='*', required=False)
answers = AnswerCreateSerializer(many=True, required=False)
attendee_name = serializers.CharField(required=False, allow_null=True)
includes_tax = serializers.BooleanField(required=False, allow_null=True)
@@ -192,8 +191,19 @@ class BaseCartPositionCreateSerializer(I18nAwareModelSerializer):
# prices, cart positions are just quota/voucher placeholders
validated_data['custom_price_input_is_net'] = not validated_data.pop('includes_tax', True)
cp = CartPosition.objects.create(event=self.context['event'], **validated_data)
cp.set_answers(answers_data, close_files=True, answercache=dict())
for answ_data in answers_data:
options = answ_data.pop('options')
if isinstance(answ_data['answer'], File):
an = answ_data.pop('answer')
answ = cp.answers.create(**answ_data, answer='')
answ.file.save(os.path.basename(an.name), an, save=False)
answ.answer = 'file://' + answ.file.name
answ.save()
an.close()
else:
answ = cp.answers.create(**answ_data)
answ.options.add(*options)
return cp
+18 -12
View File
@@ -764,6 +764,15 @@ class EventSettingsSerializer(SettingsSerializer):
'event_calendar_future_only',
'frontpage_text',
'event_info_text',
'attendee_names_asked',
'attendee_names_required',
'attendee_emails_asked',
'attendee_emails_required',
'attendee_addresses_asked',
'attendee_addresses_required',
'attendee_company_asked',
'attendee_company_required',
'attendee_data_explanation_text',
'confirm_texts',
'order_email_asked_twice',
'order_phone_asked',
@@ -932,6 +941,14 @@ class DeviceEventSettingsSerializer(EventSettingsSerializer):
'show_quota_left',
'show_dates_on_frontpage',
'max_items_per_order',
'attendee_names_asked',
'attendee_names_required',
'attendee_emails_asked',
'attendee_emails_required',
'attendee_addresses_asked',
'attendee_addresses_required',
'attendee_company_asked',
'attendee_company_required',
'ticket_download',
'ticket_download_addons',
'ticket_download_nonadm',
@@ -962,6 +979,7 @@ class DeviceEventSettingsSerializer(EventSettingsSerializer):
'reusable_media_type_nfc_mf0aes',
'reusable_media_type_nfc_mf0aes_random_uid',
'reusable_media_usage_enforced',
'system_question_order',
'tax_rule_payment',
'tax_rule_cancellation',
]
@@ -986,18 +1004,6 @@ class DeviceEventSettingsSerializer(EventSettingsSerializer):
)
)
# Provide fixed values for old configuration fields to ensure apps never use their built-in FakeQuestions, only the
# ones we provide from POSCompatQuestionViewSet
self.fields['system_question_order'] = serializers.JSONField(read_only=True, default=dict(), source='_invalid')
self.fields['attendee_names_asked'] = serializers.BooleanField(read_only=True, default=False, source='_invalid')
self.fields['attendee_names_required'] = serializers.BooleanField(read_only=True, default=False, source='_invalid')
self.fields['attendee_emails_asked'] = serializers.BooleanField(read_only=True, default=False, source='_invalid')
self.fields['attendee_emails_required'] = serializers.BooleanField(read_only=True, default=False, source='_invalid')
self.fields['attendee_addresses_asked'] = serializers.BooleanField(read_only=True, default=False, source='_invalid')
self.fields['attendee_addresses_required'] = serializers.BooleanField(read_only=True, default=False, source='_invalid')
self.fields['attendee_company_asked'] = serializers.BooleanField(read_only=True, default=False, source='_invalid')
self.fields['attendee_company_required'] = serializers.BooleanField(read_only=True, default=False, source='_invalid')
class MultiLineStringField(serializers.Field):
+3 -75
View File
@@ -32,16 +32,14 @@
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under the License.
from collections import OrderedDict, namedtuple
from collections import OrderedDict
from django.core.exceptions import ValidationError as BaseValidationError
from django.core.exceptions import ValidationError
from rest_framework import serializers
from rest_framework.fields import SerializerMethodField
from pretix.api.auth.utils import get_session_key_for_api_request
def remove_duplicates_from_list(data):
return list(OrderedDict.fromkeys(data))
@@ -97,7 +95,7 @@ class UploadedFileField(serializers.Field):
pass
elif cf.session_key != get_session_key_for_api_request(request):
self.fail('not_found')
except (BaseValidationError, IndexError): # invalid uuid
except (ValidationError, IndexError): # invalid uuid
self.fail('not_found')
except CachedFile.DoesNotExist:
self.fail('not_found')
@@ -135,73 +133,3 @@ class PluginsField(serializers.Field):
return {
'plugins': data
}
class WritableSerializerMethodField(SerializerMethodField):
"""
A field that get its representation from calling a method on the
parent serializer class. The method called will be of the form
"get_{field_name}", and should take a single argument, which is the
object being serialized.
When the field is written, a method of the form "put_{field_name}"
is called, with the instance and the incoming data as arguments. It
should return a dictionary of data to be update validated_data with.
For example:
class ExampleSerializer(Serializer):
extra_info = WritableSerializerMethodField()
def get_extra_info(self, obj):
return ... # Calculate some data to return.
def put_extra_info(self, obj, new_value):
# Store new value
"""
def __init__(self, method_name=None, put_method_name=None, **kwargs):
self.put_method_name = put_method_name
super().__init__(method_name, **kwargs)
self.read_only = False
def bind(self, field_name, parent):
# The method name defaults to `get_{field_name}`.
if self.method_name is None:
self.method_name = f'get_{field_name}'
if self.put_method_name is None:
self.put_method_name = f'put_{field_name}'
super().bind(field_name, parent)
def to_representation(self, value):
method = getattr(self.parent, self.method_name)
return method(value)
def to_internal_value(self, data):
method = getattr(self.parent, self.put_method_name)
return method(self.parent.instance, data)
class ContextAwareQueryMixin:
def __init__(self, *args, **kwargs):
assert not kwargs.get('read_only', False), (
'Scoped related fields are useless when read-only, '
'use a regular RelatedField instead.'
)
assert callable(kwargs.get('queryset', None)), (
'Scoped related fields must provide a callable `queryset`.'
)
super().__init__(*args, **kwargs)
def get_queryset(self):
return self.queryset(**self.context)
class PrimaryKeyScopedRelatedField(ContextAwareQueryMixin, serializers.PrimaryKeyRelatedField):
pass
class SlugScopedRelatedField(ContextAwareQueryMixin, serializers.SlugRelatedField):
pass
+55 -551
View File
@@ -19,8 +19,7 @@
# You should have received a copy of the GNU Affero General Public License along with this program. If not, see
# <https://www.gnu.org/licenses/>.
#
import copy
import logging
# This file is based on an earlier version of pretix which was released under the Apache License 2.0. The full text of
# the Apache License 2.0 can be obtained at <http://www.apache.org/licenses/LICENSE-2.0>.
#
@@ -34,45 +33,26 @@ import logging
# License for the specific language governing permissions and limitations under the License.
import os.path
from decimal import Decimal
from itertools import zip_longest
import rest_framework
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import transaction, models
from django.db import transaction
from django.db.models import QuerySet
from django.utils.functional import cached_property, lazy
from django.utils.translation import gettext_lazy as _
from i18nfield.rest_framework import I18nField
from i18nfield.strings import LazyI18nString
from rest_framework import serializers
from rest_framework.exceptions import ValidationError as DrfValidationError
from rest_framework.serializers import as_serializer_error
from pretix.api.compat import MergeField
from pretix.api.serializers import (
CompatDecimalField, SalesChannelMigrationMixin,
)
from pretix.api.serializers.event import MetaDataField
from pretix.api.serializers.fields import PrimaryKeyScopedRelatedField, \
UploadedFileField, \
WritableSerializerMethodField
from pretix.api.serializers.fields import UploadedFileField
from pretix.api.serializers.i18n import I18nAwareModelSerializer
from pretix.base.forms.questions import REQUIRED_NAME_PARTS
from pretix.base.models import (
Item, ItemAddOn, ItemBundle, ItemCategory, ItemMetaValue, ItemProgramTime,
ItemVariation, ItemVariationMetaValue, Question, QuestionAnswer,
QuestionOption, Quota, SalesChannel,
ItemVariation, ItemVariationMetaValue, Question, QuestionOption, Quota,
SalesChannel,
)
from pretix.base.models.items import Questionnaire, QuestionnaireRow
from pretix.base.settings import (
PERSON_NAME_SALUTATIONS, PERSON_NAME_SCHEMES, PERSON_NAME_TITLE_GROUPS, LazyI18nStringList,
)
from pretix.base.templatetags.rich_text import rich_text
from pretix.helpers.i18n import i18n_all_from_gettext
from pretix.helpers.models import is_prefetched
logger = logging.getLogger(__name__)
class InlineItemVariationSerializer(SalesChannelMigrationMixin, I18nAwareModelSerializer):
@@ -281,7 +261,9 @@ class ItemAddOnSerializer(serializers.ModelSerializer):
def validate(self, data):
data = super().validate(data)
ItemAddOn.clean_max_min_count(data.get('max_count'), data.get('min_count'))
full_data = self.to_internal_value(self.to_representation(self.instance)) if self.instance else {}
full_data.update(data)
ItemAddOn.clean_max_min_count(full_data.get('max_count'), full_data.get('min_count'))
return data
@@ -313,9 +295,6 @@ class ItemSerializer(SalesChannelMigrationMixin, I18nAwareModelSerializer):
program_times = InlineItemProgramTimeSerializer(many=True, required=False)
tax_rate = ItemTaxRateField(source='*', read_only=True, max_digits=7, decimal_places=4)
meta_data = MetaDataField(required=False, source='*')
personalized = WritableSerializerMethodField(required=False)
questionnaires = PrimaryKeyScopedRelatedField(many=True, allow_null=True, required=False,
queryset=lambda event, **kw: event.questionnaires.filter(type__startswith='position_'))
picture = UploadedFileField(required=False, allow_null=True, allowed_types=(
'image/png', 'image/jpeg', 'image/gif'
), max_size=settings.FILE_UPLOAD_MAX_SIZE_IMAGE)
@@ -343,7 +322,7 @@ class ItemSerializer(SalesChannelMigrationMixin, I18nAwareModelSerializer):
'grant_membership_duration_months', 'validity_mode', 'validity_fixed_from', 'validity_fixed_until',
'validity_dynamic_duration_minutes', 'validity_dynamic_duration_hours', 'validity_dynamic_duration_days',
'validity_dynamic_duration_months', 'validity_dynamic_start_choice', 'validity_dynamic_start_choice_day_limit',
'media_policy', 'media_type', 'questionnaires')
'media_policy', 'media_type')
read_only_fields = ('has_variations',)
def __init__(self, *args, **kwargs):
@@ -356,36 +335,6 @@ class ItemSerializer(SalesChannelMigrationMixin, I18nAwareModelSerializer):
self.fields['limit_sales_channels'].child_relation.queryset = self.context['event'].organizer.sales_channels.all()
self.fields['variations'].child.fields['limit_sales_channels'].child_relation.queryset = self.context['event'].organizer.sales_channels.all()
def get_personalized(self, item):
if is_prefetched(item.questionnaires):
if all(hasattr(q, 'has_attendee_data') for q in item.questionnaires.all()):
return any(q.has_attendee_data for q in item.questionnaires.all())
return QuestionnaireRow.objects.filter(questionnaire__items=item, system_datafield__in=('@attendee_name_parts', '@attendee_email')).exists()
def put_personalized(self, item, new_value):
if item and new_value != self.get_personalized(item):
raise ValidationError({'personalized': 'Deprecated field "personalized" can not be updated.'})
if new_value and not item:
try:
return {'questionnaires': [self._get_or_create_compat_personalization_questionnaire()]}
except Questionnaire.DoesNotExist:
raise ValidationError({'personalized': 'To create new products with personalized=True, a questionnaire named "Attendee data" must exist.'})
return {}
def _get_or_create_compat_personalization_questionnaire(self):
event = self.context['request'].event
try:
return event.questionnaires.get(type=Questionnaire.QuestionnaireType.POSITION_PURCHASE, compat_personalization=True)
except Questionnaire.DoesNotExist:
q = event.questionnaires.create(internal_name=str(_('Attendee data')), type=Questionnaire.QuestionnaireType.POSITION_PURCHASE, position=0, compat_personalization=True)
system_datafields_asked = {df: (label, helptext, required) for df, label, helptext, required in QuestionnaireRow.objects.filter(
questionnaire__event=event, system_datafield__isnull=False, questionnaire__type=Questionnaire.QuestionnaireType.POSITION_PURCHASE
).values_list('system_datafield', 'label', 'help_text', 'required')}
for i, (df, (label, helptext, required)) in enumerate(system_datafields_asked.items()):
q.rows.create(label=label, help_text=helptext, required=required, system_datafield=df, position=i)
return q
def validate(self, data):
data = super().validate(data)
if self.instance and ('addons' in data or 'variations' in data or 'bundles' in data or 'program_times' in data):
@@ -396,6 +345,15 @@ class ItemSerializer(SalesChannelMigrationMixin, I18nAwareModelSerializer):
Item.clean_available(data.get('available_from'), data.get('available_until'))
Item.clean_media_settings(self.context['event'], data.get('media_policy'), data.get('media_type'), data.get('issue_giftcard'))
if data.get('personalized') and not data.get('admission'):
raise ValidationError(_('Only admission products can currently be personalized.'))
if data.get('admission') and 'personalized' not in data and not self.instance:
# Backwards compatibility
data['personalized'] = True
elif 'admission' in data and not data['admission']:
data['personalized'] = False
if data.get('issue_giftcard'):
if data.get('tax_rule') and data.get('tax_rule').rate > 0:
raise ValidationError(
@@ -461,11 +419,9 @@ class ItemSerializer(SalesChannelMigrationMixin, I18nAwareModelSerializer):
picture = validated_data.pop('picture', None)
require_membership_types = validated_data.pop('require_membership_types', [])
limit_sales_channels = validated_data.pop('limit_sales_channels', [])
questionnaires = validated_data.pop('questionnaires', [])
item = Item.objects.create(**validated_data)
if limit_sales_channels and not validated_data.get('all_sales_channels'):
item.limit_sales_channels.add(*limit_sales_channels)
item.questionnaires.add(*questionnaires)
if picture:
item.picture.save(os.path.basename(picture.name), picture)
if require_membership_types:
@@ -504,7 +460,6 @@ class ItemSerializer(SalesChannelMigrationMixin, I18nAwareModelSerializer):
value=value,
item=item
)
return item
def update(self, instance, validated_data):
@@ -577,150 +532,27 @@ class InlineQuestionOptionSerializer(I18nAwareModelSerializer):
fields = ('id', 'identifier', 'answer', 'position')
class DatafieldRelatedField(serializers.SlugRelatedField):
default_error_messages = {
'invalid_choice': _('"{input}" is not a valid choice.')
}
def __init__(self, *args, **kwargs):
super().__init__(slug_field='identifier', **kwargs)
def get_queryset(self):
return self.context['event'].questions.all()
def to_representation(self, qc):
if not qc:
return None
elif qc.system_datafield:
return qc.system_datafield
elif qc.user_datafield_id:
return qc.user_datafield.identifier
else:
return None
def to_internal_value(self, data):
if data is None:
return {'user_datafield': None, 'system_datafield': None}
elif type(data) == str and data.startswith('@'):
if data not in QuestionnaireRow.SystemDatafield.values:
self.fail("invalid_choice", input=data)
return {'user_datafield': None, 'system_datafield': data}
elif type(data) == str:
return {'user_datafield': super().to_internal_value(data), 'system_datafield': None}
else:
self.fail('incorrect_type', data_type=type(data).__name__)
def use_pk_only_optimization(self):
return self.source == '*'
class LegacyDependencyValueField(serializers.CharField):
def to_representation(self, obj):
return obj[0] if obj else None
class QuestionFormSerializer(I18nAwareModelSerializer):
datafield = DatafieldRelatedField(allow_null=True, source='*')
question = I18nField(source='label', allow_null=True)
type = serializers.CharField(source='user_datafield.type', allow_null=True, default=Question.FieldType.STRING)
identifier = serializers.SerializerMethodField(read_only=True)
show_during_checkin = serializers.BooleanField(source='user_datafield.show_during_checkin', allow_null=True, default=False)
print_on_invoice = serializers.BooleanField(source='user_datafield.print_on_invoice', allow_null=True, default=False)
valid_number_min = serializers.IntegerField(source='user_datafield.valid_number_min', allow_null=True)
valid_number_max = serializers.IntegerField(source='user_datafield.valid_number_max', allow_null=True)
valid_date_min = serializers.DateField(source='user_datafield.valid_date_min', allow_null=True)
valid_date_max = serializers.DateField(source='user_datafield.valid_date_max', allow_null=True)
valid_datetime_min = serializers.DateTimeField(source='user_datafield.valid_datetime_min', allow_null=True)
valid_datetime_max = serializers.DateTimeField(source='user_datafield.valid_datetime_max', allow_null=True)
valid_string_length_max = serializers.IntegerField(source='user_datafield.valid_string_length_max', allow_null=True)
valid_string_length_min = serializers.IntegerField(source='user_datafield.valid_string_length_min', allow_null=True)
valid_file_portrait = serializers.BooleanField(source='user_datafield.valid_file_portrait', allow_null=True)
dependency_question = DatafieldRelatedField(allow_null=True, required=False)
items = serializers.PrimaryKeyRelatedField(source='questionnaire.items', many=True, queryset=Item.objects.none(), allow_null=True, required=False)
questionnaire_id = serializers.IntegerField(source='questionnaire.id', read_only=True)
options = InlineQuestionOptionSerializer(source='user_datafield.options', many=True, required=False, default=[])
class Meta:
model = QuestionnaireRow
fields = ('datafield', 'label', 'type', 'required', 'help_text', 'items', 'options', 'position',
'show_during_checkin', 'identifier', 'dependency_question', 'dependency_values',
'print_on_invoice', 'valid_number_min',
'valid_number_max', 'valid_date_min', 'valid_date_max', 'valid_datetime_min', 'valid_datetime_max',
'valid_string_length_max', 'valid_string_length_min', 'valid_file_portrait', 'questionnaire_id')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['items'].child_relation.queryset = self.context['event'].items.all() if 'event' in self.context else Item.objects.none()
def get_attribute(self, instance):
if isinstance(instance, QuestionAnswer):
position = instance.cartposition if instance.cartposition_id else instance.orderposition
qcs = list(QuestionnaireRow.objects.filter(user_datafield_id=instance.question_id, questionnaire__items__in=[position.item_id]))
return next((qc for qc in qcs if qc.questionnaire.type == self.context.get('preferred_questionnaire_type', Questionnaire.QuestionnaireType.POSITION_PURCHASE)), qcs[0])
return super().get_attribute(instance)
def cook_dependency_question_id(self, qc):
if qc.dependency_question:
return qc.dependency_question.cooked_id
else:
return None
def get_identifier(self, qc):
return qc.user_datafield.identifier if qc.user_datafield else qc.system_datafield
@property
def data(self):
results = super().data
mangled_results = []
pos_offset = 0
for row in results:
row['position'] += pos_offset
if row['identifier'] == '@attendee_name_parts' and self.context.get('expand_attendee_name'):
settings = self.context['event'].settings
for k, v, w, *__ in PERSON_NAME_SCHEMES.get(settings.name_scheme)['fields']:
part = dict(row)
part["identifier"] += ":" + k
part["question"] = i18n_all_from_gettext(v, settings.locales)
if k == "title" and settings.name_scheme_titles:
part["type"] = Question.FieldType.CHOICE
part["options"] = [{"id": idx + 1, "identifier": k, "answer": i18n_all_from_gettext(k, settings.locales), "position": idx + 1} for idx, k in
enumerate(PERSON_NAME_TITLE_GROUPS.get(settings.name_scheme_titles)[1])]
elif k == "salutation":
part["type"] = Question.FieldType.CHOICE
part["options"] = [{"id": idx + 1, "identifier": k, "answer": i18n_all_from_gettext(v, settings.locales), "position": idx + 1} for idx, (k, v) in
enumerate(PERSON_NAME_SALUTATIONS)]
part["id"] = QuestionnaireRow.cook_id_from_parts(row['questionnaire_id'], None, part["identifier"])
part["required"] = part["required"] and k in REQUIRED_NAME_PARTS
mangled_results.append(part)
pos_offset += 1
row["position"] += 1
else:
if row['identifier'] == '@country':
row['type'] = Question.FieldType.COUNTRYCODE
mangled_results.append(row)
return mangled_results
def to_internal_value(self, data):
return [data] if data else []
class DatafieldSerializer(I18nAwareModelSerializer):
class QuestionSerializer(I18nAwareModelSerializer):
options = InlineQuestionOptionSerializer(many=True, required=False)
identifier = serializers.CharField(allow_null=True)
#referenced_by_questionnaires = MergeField('referenced_by', serializers.IntegerField(source='questionnaire.id'), mode='list')
#questionnaire_types = MergeField('referenced_by', serializers.CharField(source='questionnaire.type'), mode='list')
dependency_value = LegacyDependencyValueField(source='dependency_values', required=False, allow_null=True)
class Meta:
model = Question
fields = ('id', 'internal_name', 'identifier', 'type',
'show_during_checkin',
'print_on_invoice', 'print_on_invoice_label', 'valid_number_min',
fields = ('id', 'question', 'type', 'required', 'items', 'options', 'position',
'ask_during_checkin', 'show_during_checkin', 'identifier', 'dependency_question', 'dependency_values',
'hidden', 'dependency_value', 'print_on_invoice', 'help_text', 'valid_number_min',
'valid_number_max', 'valid_date_min', 'valid_date_max', 'valid_datetime_min', 'valid_datetime_max',
'valid_string_length_max', 'valid_string_length_min', 'valid_file_portrait',
#'referenced_by_questionnaires', 'questionnaire_types',
'options')
'valid_string_length_max', 'valid_string_length_min', 'valid_file_portrait')
def validate_identifier(self, value):
Question._clean_identifier(self.context['event'], value, self.instance)
@@ -731,6 +563,14 @@ class DatafieldSerializer(I18nAwareModelSerializer):
self.instance.clean_type_change(self.instance.type, value)
return value
def validate_dependency_question(self, value):
if value:
if value.type not in (Question.TYPE_CHOICE, Question.TYPE_BOOLEAN, Question.TYPE_CHOICE_MULTIPLE):
raise ValidationError('Question dependencies can only be set to boolean or choice questions.')
if value == self.instance:
raise ValidationError('A question cannot depend on itself.')
return value
def validate(self, data):
data = super().validate(data)
if self.instance and 'options' in data:
@@ -742,6 +582,24 @@ class DatafieldSerializer(I18nAwareModelSerializer):
full_data = self.to_internal_value(self.to_representation(self.instance)) if self.instance else {}
full_data.update(data)
if full_data.get('ask_during_checkin') and full_data.get('dependency_question'):
raise ValidationError('Dependencies are not supported during check-in.')
dep = full_data.get('dependency_question')
if dep:
if dep.ask_during_checkin:
raise ValidationError(_('Question cannot depend on a question asked during check-in.'))
seen_ids = {self.instance.pk} if self.instance else set()
while dep:
if dep.pk in seen_ids:
raise ValidationError(_('Circular dependency between questions detected.'))
seen_ids.add(dep.pk)
dep = dep.dependency_question
if full_data.get('ask_during_checkin') and full_data.get('type') in Question.ASK_DURING_CHECKIN_UNSUPPORTED:
raise ValidationError(_('This type of question cannot be asked during check-in.'))
if full_data.get('show_during_checkin') and full_data.get('type') in Question.SHOW_DURING_CHECKIN_UNSUPPORTED:
raise ValidationError(_('This type of question cannot be shown during check-in.'))
@@ -761,369 +619,15 @@ class DatafieldSerializer(I18nAwareModelSerializer):
@transaction.atomic
def create(self, validated_data):
options_data = validated_data.pop('options') if 'options' in validated_data else []
items = validated_data.pop('items', [])
question = Question.objects.create(**validated_data, container_type=self.context['container_type'])
question = Question.objects.create(**validated_data, container_type=Question.ContainerType.ORDERPOSITION)
question.items.set(items)
for opt_data in options_data:
QuestionOption.objects.create(question=question, **opt_data)
return question
class CompatQuestionSerializer(DatafieldSerializer):
question = MergeField('referenced_by', I18nField(source='label'), mode='consensus')
required = MergeField('referenced_by', serializers.BooleanField(), mode='consensus')
items = MergeField('referenced_by', serializers.PrimaryKeyRelatedField(source='questionnaire.items', many=True, queryset=Item.objects.none(), allow_null=True, required=False), mode='union')
position = serializers.IntegerField(required=False, read_only=True, default=0)
ask_during_checkin = MergeField('referenced_by', serializers.BooleanField(source='questionnaire.ask_during_checkin'), mode='bool_or')
hidden = MergeField('referenced_by', serializers.BooleanField(source='questionnaire.hidden'), mode='bool_or')
dependency_question = MergeField('referenced_by', serializers.IntegerField(source='dependency_question.user_datafield_id', required=False, default=None, allow_null=True), mode='consensus')
dependency_values = MergeField('referenced_by', serializers.JSONField(), mode='consensus')
dependency_value = MergeField('referenced_by', LegacyDependencyValueField(source='dependency_values'), mode='consensus')
help_text = MergeField('referenced_by', I18nField(), mode='consensus')
class Meta:
model = Question
fields = (
'id', 'question', 'type', 'required', 'items', 'options', 'position',
'ask_during_checkin', 'show_during_checkin', 'identifier', 'dependency_question', 'dependency_values',
'hidden', 'dependency_value', 'print_on_invoice', 'help_text', 'valid_number_min',
'valid_number_max', 'valid_date_min', 'valid_date_max', 'valid_datetime_min', 'valid_datetime_max',
'valid_string_length_max', 'valid_string_length_min', 'valid_file_portrait',
# new
#'internal_name', 'referenced_by_questionnaires', 'questionnaire_types',
)
def __init__(self, *args, **kwargs):
self.fields['items'].inner_field.child_relation.queryset = kwargs['context']['event'].items.all()
super().__init__(*args, **kwargs)
class POSCompatQuestionSerializer(QuestionFormSerializer):
id = serializers.IntegerField(source='cooked_id', read_only=True)
question = I18nField(source='label', allow_null=True)
type = serializers.CharField(source='user_datafield.type', allow_null=True, default=Question.FieldType.STRING)
identifier = serializers.SerializerMethodField(read_only=True)
show_during_checkin = serializers.BooleanField(source='user_datafield.show_during_checkin', allow_null=True, default=False)
ask_during_checkin = serializers.BooleanField(source='questionnaire.ask_during_checkin')
hidden = serializers.BooleanField(source='questionnaire.hidden')
print_on_invoice = serializers.BooleanField(source='user_datafield.print_on_invoice', allow_null=True, default=False)
valid_number_min = serializers.IntegerField(source='user_datafield.valid_number_min', allow_null=True)
valid_number_max = serializers.IntegerField(source='user_datafield.valid_number_max', allow_null=True)
valid_date_min = serializers.DateField(source='user_datafield.valid_date_min', allow_null=True)
valid_date_max = serializers.DateField(source='user_datafield.valid_date_max', allow_null=True)
valid_datetime_min = serializers.DateTimeField(source='user_datafield.valid_datetime_min', allow_null=True)
valid_datetime_max = serializers.DateTimeField(source='user_datafield.valid_datetime_max', allow_null=True)
valid_string_length_max = serializers.IntegerField(source='user_datafield.valid_string_length_max', allow_null=True)
valid_string_length_min = serializers.IntegerField(source='user_datafield.valid_string_length_min', allow_null=True)
valid_file_portrait = serializers.BooleanField(source='user_datafield.valid_file_portrait', allow_null=True)
dependency_question = serializers.SerializerMethodField('cook_dependency_question_id', read_only=True)
dependency_value = serializers.SerializerMethodField('empty', read_only=True)
position = serializers.SerializerMethodField(read_only=True)
items = serializers.PrimaryKeyRelatedField(source='questionnaire.items', many=True, queryset=Item.objects.none(), allow_null=True, required=False)
questionnaire_id = serializers.IntegerField(source='questionnaire.id', read_only=True)
options = InlineQuestionOptionSerializer(source='user_datafield.options', many=True, required=False, default=[])
class Meta:
model = QuestionnaireRow
fields = ('id', 'question', 'type', 'required', 'items', 'options', 'position',
'ask_during_checkin', 'show_during_checkin', 'identifier', 'dependency_question', 'dependency_values',
'hidden', 'dependency_value', 'print_on_invoice', 'help_text', 'valid_number_min',
'valid_number_max', 'valid_date_min', 'valid_date_max', 'valid_datetime_min', 'valid_datetime_max',
'valid_string_length_max', 'valid_string_length_min', 'valid_file_portrait', 'questionnaire_id')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['items'].child_relation.queryset = self.context['event'].items.all() if 'event' in self.context else Item.objects.none()
def get_attribute(self, instance):
if isinstance(instance, QuestionAnswer):
position = instance.cartposition if instance.cartposition_id else instance.orderposition
print('searching ', repr(instance), repr(position), repr(instance.question), instance.pk, position.item_id, self.context) # TODO remove print
qcs = list(QuestionnaireRow.objects.filter(user_datafield_id=instance.question_id, questionnaire__items__in=[position.item_id]))
return next((qc for qc in qcs if qc.questionnaire.type == self.context.get('preferred_questionnaire_type', Questionnaire.QuestionnaireType.POSITION_PURCHASE)), qcs[0])
return super().get_attribute(instance)
def cook_dependency_question_id(self, qc):
if qc.dependency_question:
return qc.dependency_question.cooked_id
else:
return None
def get_identifier(self, qc):
return qc.user_datafield.identifier if qc.user_datafield else qc.system_datafield
def empty(self, qc):
return None
def get_position(self, qc):
return qc.questionnaire.position * 1000000000 + qc.position
@staticmethod
def mangle_results(event, results):
mangled_results = []
pos_offset = 0
for row in results:
row['position'] += pos_offset
if row['identifier'] == '@attendee_name_parts':
settings = event.settings
for k, v, w, *__ in PERSON_NAME_SCHEMES.get(settings.name_scheme)['fields']:
part = dict(row)
part["identifier"] += ":" + k
part["question"] = i18n_all_from_gettext(v, settings.locales)
if k == "title" and settings.name_scheme_titles:
part["type"] = Question.FieldType.CHOICE
part["options"] = [{"id": idx + 1, "identifier": k, "answer": i18n_all_from_gettext(k, settings.locales), "position": idx + 1} for idx, k in
enumerate(PERSON_NAME_TITLE_GROUPS.get(settings.name_scheme_titles)[1])]
elif k == "salutation":
part["type"] = Question.FieldType.CHOICE
part["options"] = [{"id": idx + 1, "identifier": k, "answer": i18n_all_from_gettext(v, settings.locales), "position": idx + 1} for idx, (k, v) in
enumerate(PERSON_NAME_SALUTATIONS)]
part["id"] = QuestionnaireRow.cook_id_from_parts(row['questionnaire_id'], None, part["identifier"])
part["required"] = part["required"] and k in REQUIRED_NAME_PARTS
mangled_results.append(part)
pos_offset += 1
row["position"] += 1
else:
if row['identifier'] == '@country':
row['type'] = Question.FieldType.COUNTRYCODE
mangled_results.append(row)
return mangled_results
class RenderedMarkdownField(serializers.CharField):
def to_representation(self, value):
return rich_text(value)
class InlineUserDatafieldSerializer(I18nAwareModelSerializer):
options = InlineQuestionOptionSerializer(many=True, required=False)
identifier = serializers.CharField(allow_null=True)
class Meta:
model = Question
fields = ('id', 'internal_name', 'identifier', 'type',
'show_during_checkin',
'print_on_invoice', 'print_on_invoice_label', 'valid_number_min',
'valid_number_max', 'valid_date_min', 'valid_date_max', 'valid_datetime_min', 'valid_datetime_max',
'valid_string_length_max', 'valid_string_length_min', 'valid_file_portrait', 'options')
class InlineDatafieldField(serializers.Field):
def to_representation(self, value):
if value.user_datafield:
return DatafieldSerializer().to_representation(instance=value.user_datafield)
elif value.system_datafield:
part = {
'show_during_checkin': False,
'print_on_invoice': False,
'print_on_invoice_label': {},
'valid_number_min': None,
'valid_number_max': None,
'valid_date_min': None,
'valid_date_max': None,
'valid_datetime_min': None,
'valid_datetime_max': None,
'valid_string_length_max': None,
'valid_string_length_min': None,
'valid_file_portrait': False,
'options': []
}
if value.system_datafield.startswith('@attendee_name_parts:'):
settings = self.context['event'].settings
part["type"] = "S"
for fieldname, label, *__ in PERSON_NAME_SCHEMES.get(settings.name_scheme)['fields']:
if fieldname != value.system_datafield.split(":")[1]:
continue
part["internal_name"] = str(QuestionnaireRow.SystemDatafield(value.system_datafield.split(":")[0]).label) + ": " + str(label)
if fieldname == "title" and settings.name_scheme_titles:
part["type"] = Question.FieldType.CHOICE
part["options"] = [
{"id": None, "identifier": k, "answer": i18n_all_from_gettext(k, settings.locales),
"position": idx + 1} for idx, k in
enumerate(PERSON_NAME_TITLE_GROUPS.get(settings.name_scheme_titles)[1])
]
elif fieldname == "salutation":
part["type"] = Question.FieldType.CHOICE
part["options"] = [
{"id": None, "identifier": k, "answer": i18n_all_from_gettext(v, settings.locales),
"position": idx + 1} for idx, (k, v) in
enumerate(PERSON_NAME_SALUTATIONS)
]
return {
'id': None,
'identifier': value.system_datafield,
**part,
}
else:
return {
'id': None,
'internal_name': str(QuestionnaireRow.SystemDatafield(value.system_datafield).label),
'identifier': value.system_datafield,
'type': QuestionnaireRow.SYSTEM_DATAFIELD_TYPES[value.system_datafield],
**part,
}
class InlineQuestionnaireRowListSerializer(serializers.ListSerializer):
def expanded_rows(self, data):
for r in data:
if r.system_datafield == '@attendee_name_parts':
settings = self.context['event'].settings
for k, v, w, *__ in PERSON_NAME_SCHEMES.get(settings.name_scheme)['fields']:
copied = copy.copy(r)
copied.system_datafield = r.system_datafield + ":" + k
labels = LazyI18nString.from_gettext(v).data
copied.label = LazyI18nString({
locale: r.label.localize(locale) + ": " + labels[locale] for locale in r.label.data
})
copied.required = r.required and k in REQUIRED_NAME_PARTS
yield copied
else:
yield r
def to_representation(self, data):
iterable = data.all() if isinstance(data, models.manager.BaseManager) else data
if self.context.get("expand_name_fields"):
iterable = self.expanded_rows(iterable)
return [
self.child.to_representation(item) for item in iterable
]
class InlineQuestionnaireRowSerializer(I18nAwareModelSerializer):
datafield = DatafieldRelatedField(allow_null=True, source='*')
dependency_datafield = DatafieldRelatedField(allow_null=True, required=False, source='dependency_question')
rendered_help_text = RenderedMarkdownField(read_only=True, source='help_text')
cooked_id = serializers.IntegerField(read_only=True, allow_null=True)
class Meta:
model = QuestionnaireRow
fields = ('datafield', 'required', 'label', 'help_text', 'dependency_datafield', 'dependency_values', 'rendered_help_text', 'cooked_id')
list_serializer_class = InlineQuestionnaireRowListSerializer
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if "rows.datafield" in self.context.get("expand", {}):
self.fields["datafield"] = InlineDatafieldField(read_only=True, source='*')
def validate_dependency_question(self, value):
if value:
if value['user_datafield']:
if value['user_datafield'].type not in Question.TYPES_ALLOWED_AS_DEPENDENCIES:
raise ValidationError('Question dependencies can only be set to boolean or choice questions.')
return value
class QuestionnaireSerializer(I18nAwareModelSerializer):
items = serializers.PrimaryKeyRelatedField(many=True, queryset=Item.objects.none(), allow_null=True, required=False)
limit_sales_channels = serializers.SlugRelatedField(
slug_field="identifier",
queryset=SalesChannel.objects.none(),
required=False,
allow_empty=True,
many=True,
)
class Meta:
model = Questionnaire
fields = ('id', 'type', 'internal_name', 'items', 'position', 'all_sales_channels', 'limit_sales_channels', 'compat_personalization', 'rows')
read_only_fields = ('compat_personalization', )
def __init__(self, *args, **kwargs):
self.fields['items'].child_relation.queryset = kwargs['context']['event'].items.all()
self.fields['limit_sales_channels'].child_relation.queryset = kwargs['context']['event'].organizer.sales_channels.all()
super().__init__(*args, **kwargs)
self.fields['rows'] = InlineQuestionnaireRowSerializer(
many=True, required=True, context=kwargs['context'], partial=False
)
def validate(self, data):
data = super().validate(data)
if self.context.get('expand_name_fields'):
raise ValidationError("Expanding of name fields is not supported on write.")
try:
full_data = self.to_internal_value(self.to_representation(self.instance)) if self.instance else {}
full_data.update(data)
except rest_framework.exceptions.ValidationError as e:
# we already have invalid state in the database, what should we do? hope it gets better after saving?
logger.exception("Invalid state in database, ignoring some validations!")
else:
if full_data.get('type') == Questionnaire.QuestionnaireType.POSITION_CHECKIN:
if any(c.get('dependency_question') for c in full_data['rows']):
raise ValidationError('Dependencies are not supported during check-in.')
if any(c.get('user_datafield') and c.get('user_datafield').type in Question.ASK_DURING_CHECKIN_UNSUPPORTED for c in full_data['rows']):
raise ValidationError(_('This type of question cannot be asked during check-in.'))
if (not full_data.get('type').startswith('position_')
and any(c['system_datafield'] for c in full_data['rows'])):
raise ValidationError('System data fields are only supported on order positions.')
system_fields = set(c['system_datafield'] for c in full_data['rows'])
if ('@zipcode' in system_fields or '@state' in system_fields or '@street' in system_fields or '@city' in system_fields) and '@country' not in system_fields:
raise ValidationError('The system data fields "street", "zip code", "city", and "state" can only be used in combination with the "country" field.')
return data
@transaction.atomic
def create(self, validated_data):
rows_data = validated_data.pop('rows') if 'rows' in validated_data else []
questionnaire = super().create(validated_data)
self.set_rows(questionnaire, rows_data)
try:
Questionnaire.check_constraints(questionnaire.event)
except ValidationError as e:
raise DrfValidationError(as_serializer_error(e))
return questionnaire
@transaction.atomic
def update(self, instance, validated_data):
rows_data = validated_data.pop('rows', None)
questionnaire = super().update(instance, validated_data)
try:
if rows_data is not None:
self.set_rows(questionnaire, rows_data)
Questionnaire.check_constraints(questionnaire.event)
except ValidationError as e:
raise DrfValidationError(as_serializer_error(e))
return questionnaire
def set_rows(self, questionnaire, new_data):
result = {}
child_serializer = self.fields['rows'].child
existing_rows = questionnaire.rows.all()
def q(qc):
return qc['user_datafield'] or qc['system_datafield']
for i, d in enumerate(new_data):
d['questionnaire'] = questionnaire
d['position'] = i + 1
d.setdefault('required', False)
d.setdefault('help_text', None)
d.setdefault('dependency_question', None)
d.setdefault('dependency_values', None)
for existing, update_data in zip_longest(existing_rows, new_data):
if update_data:
if update_data.get('dependency_question'):
try:
update_data['dependency_question'] = result[q(update_data['dependency_question'])]
except KeyError:
raise ValidationError('A question can only depend on a previous question from the same questionnaire.')
if update_data['dependency_question'].datafield_type not in Question.TYPES_ALLOWED_AS_DEPENDENCIES:
raise ValidationError('A question can only depend on a boolean or choice question.')
if existing:
result[q(update_data)] = child_serializer.update(existing, update_data)
else:
result[q(update_data)] = child_serializer.create(update_data)
else:
existing.delete()
return result
class QuotaSerializer(I18nAwareModelSerializer):
available = serializers.BooleanField(read_only=True)
available_number = serializers.IntegerField(read_only=True)
+70 -278
View File
@@ -21,14 +21,14 @@
#
import json
import logging
import os
from collections import Counter, defaultdict
from contextlib import nullcontext
from datetime import timedelta
from decimal import Decimal
import pycountry
from django.conf import settings
from django.core.exceptions import ValidationError as BaseValidationError
from django.core.files import File
from django.db import models
from django.db.models import F, Q
from django.utils.encoding import force_str
@@ -38,19 +38,16 @@ from django_countries.fields import Country
from django_scopes import scopes_disabled
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from rest_framework.fields import get_attribute
from rest_framework.relations import SlugRelatedField
from rest_framework.reverse import reverse
from rest_framework.serializers import ListSerializer
from pretix.api.auth.utils import get_session_key_for_api_request
from pretix.api.serializers import CompatDecimalField, CompatibleJSONField
from pretix.api.serializers.event import SubEventSerializer
from pretix.api.serializers.fields import PrimaryKeyScopedRelatedField, SlugScopedRelatedField
from pretix.api.serializers.forms import form_field_to_serializer_field
from pretix.api.serializers.i18n import I18nAwareModelSerializer
from pretix.api.serializers.item import (
InlineItemVariationSerializer, ItemSerializer, POSCompatQuestionSerializer,
InlineItemVariationSerializer, ItemSerializer, QuestionSerializer,
)
from pretix.api.signals import order_api_details, orderposition_api_details
from pretix.base.decimal import round_decimal
@@ -60,8 +57,8 @@ from pretix.base.media import MEDIA_TYPES
from pretix.base.models import (
CachedFile, Checkin, Customer, Device, GiftCard, Invoice, InvoiceAddress,
InvoiceLine, Item, ItemVariation, Order, OrderPosition, Question,
QuestionAnswer, QuestionnaireRow, ReusableMedium, SalesChannel, Seat,
SubEvent, TaxRule, Voucher,
QuestionAnswer, ReusableMedium, SalesChannel, Seat, SubEvent, TaxRule,
Voucher,
)
from pretix.base.models.orders import (
BlockedTicketSecret, CartPosition, OrderFee, OrderPayment, OrderRefund,
@@ -77,13 +74,11 @@ from pretix.base.services.pricing import (
)
from pretix.base.services.quotas import QuotaAvailability
from pretix.base.settings import (
COUNTRIES_WITH_STATE_IN_ADDRESS, PERSON_NAME_SALUTATIONS,
PERSON_NAME_SCHEMES, PERSON_NAME_TITLE_GROUPS, ROUNDING_MODES,
COUNTRIES_WITH_STATE_IN_ADDRESS, ROUNDING_MODES,
)
from pretix.base.signals import register_ticket_outputs
from pretix.helpers.countries import CachedCountries
from pretix.multidomain.urlreverse import eventreverse_absolute
from pretix.testutils.queries import assert_num_queries
logger = logging.getLogger(__name__)
@@ -215,23 +210,17 @@ class InvoiceAddressSerializer(I18nAwareModelSerializer):
return data
class AnswerQuestionOptionsIdentifierField(serializers.Field):
default_error_messages = {
'invalid_choice': gettext_lazy('"{input}" is not a valid choice.')
}
class AnswerQuestionIdentifierField(serializers.Field):
def to_representation(self, instance: QuestionAnswer):
return instance.question.identifier
class AnswerQuestionOptionsIdentifierField(serializers.Field):
def to_representation(self, instance: QuestionAnswer):
if isinstance(instance, WrappedModel) or instance.pk:
return [o.identifier for o in instance.options.all()]
return []
def to_internal_value(self, data):
if not isinstance(data, list):
self.fail('invalid_choice', input=data)
if not all(isinstance(i, str) for i in data):
self.fail('invalid_choice', input=data)
return {self.field_name: data}
class InlineSeatSerializer(I18nAwareModelSerializer):
@@ -240,153 +229,9 @@ class InlineSeatSerializer(I18nAwareModelSerializer):
fields = ('id', 'name', 'seat_guid', 'zone_name', 'row_name', 'row_label', 'seat_label', 'seat_number')
class MixedAnswerListSerializer(ListSerializer):
def __init__(self, instance=None, *args, **kwargs):
super().__init__(instance.answers if instance else None, *args, **kwargs)
def get_value(self, dictionary):
return dictionary
def is_compat_request(self):
if request := self.context.get('request'):
if 'compat_answers' in request.query_params:
return request.query_params.get('compat_answers').lower() == 'true'
return (isinstance(request.auth, Device) and (request.auth.software_brand or '').startswith('pretixPOS'))
def add_compat_answers(self, answers, container_obj):
answers_dict = {answer["question"]: answer for answer in answers}
for qc in getattr(container_obj, 'relevant_questionnaires', QuestionnaireRow.objects.filter(
Q(system_datafield__isnull=False) | Q(user_datafield_id__isnull=False),
questionnaire__items__id=container_obj.item_id
)):
if qc.user_datafield_id:
if answer := answers_dict.get(qc.user_datafield_id):
answer = dict(answer)
answer["question"] = qc.cooked_id
answer["questionnaire_id"] = qc.questionnaire_id
answers.append(answer)
elif qc.system_datafield and (sys_answer := container_obj.system_answers[qc.system_datafield]) is not None:
if qc.system_datafield == QuestionnaireRow.SystemDatafield.ATTENDEE_NAME_PARTS:
name_parts = container_obj.attendee_name_parts
settings = self.context['event'].settings
for k, v, w, *__ in PERSON_NAME_SCHEMES.get(settings.name_scheme)['fields']:
if k in name_parts:
options = []
options_ident = []
try:
if k == "salutation":
salutation_keys = [key for key, value in PERSON_NAME_SALUTATIONS]
options = [salutation_keys.index(name_parts[k]) + 1]
options_ident = [name_parts[k]]
elif k == "title" and settings.name_scheme_titles:
options = [PERSON_NAME_TITLE_GROUPS.get(settings.name_scheme_titles)[1].index(name_parts[k]) + 1]
options_ident = [name_parts[k]]
except ValueError:
pass
answers.append({
"question": QuestionnaireRow.cook_id_from_parts(qc.questionnaire_id, None, f'{qc.system_datafield}:{k}'),
"answer": name_parts[k],
"question_identifier": f'{qc.system_datafield}:{k}',
"datafield": f'{qc.system_datafield}:{k}',
"options": options,
"option_identifiers": options_ident,
"questionnaire_id": qc.questionnaire_id,
})
answers.append({
"question": qc.cooked_id,
"answer": sys_answer,
"question_identifier": f'{qc.system_datafield}',
"datafield": f'{qc.system_datafield}',
"options": [],
"option_identifiers": [],
"questionnaire_id": qc.questionnaire_id,
})
def to_representation(self, data):
try:
answers_qs = get_attribute(data, ['answers'])
except (KeyError, AttributeError):
return None
answers = super().to_representation(answers_qs)
if self.is_compat_request():
self.add_compat_answers(answers, data)
return answers
def run_child_validation(self, data):
answer = data
settings = self.context['event'].settings
if "question" in answer or ("datafield" in answer and answer["datafield"] in QuestionnaireRow.SYSTEM_DATAFIELD_NUMBERS):
if "question" in answer:
qid, dfid, sys_df = QuestionnaireRow.uncook_id(answer["question"])
else:
qid, dfid, sys_df = None, None, answer["datafield"]
if self.context.get('allowed_datafields') and (dfid or sys_df.split(':')[0]) not in self.context.get('allowed_datafields'): # TODO maybe move this into the to_internal_value loop
raise ValidationError(f"Unexpected data field {dfid or sys_df}")
if dfid is not None:
answer["question"] = dfid
return super().run_child_validation(answer)
elif sys_df == "@country":
country = Country(answer["answer"])
if not country.name:
raise ValidationError("Data field @country needs a valid country code.")
return ('country', country)
elif sys_df == "@attendee_name_parts:salutation":
valid_salutations = dict(PERSON_NAME_SALUTATIONS)
if "options" in answer and len(answer["options"]) == 1 and answer["options"][0] <= len(PERSON_NAME_SALUTATIONS):
salutation = PERSON_NAME_SALUTATIONS[answer["options"][0] - 1][0]
elif "option_identifiers" in answer and len(answer["option_identifiers"]) == 1 and answer["option_identifiers"][0] in valid_salutations:
salutation = answer["option_identifiers"][0]
else:
raise ValidationError("Data field @attendee_name_parts:salutation requires valid options")
return ('attendee_name_parts', {'salutation': salutation})
elif sys_df == "@attendee_name_parts:title" and settings.name_scheme_titles:
valid_titles = PERSON_NAME_TITLE_GROUPS.get(settings.name_scheme_titles)[1]
if "options" in answer and len(answer["options"]) == 1 and answer["options"][0] <= len(valid_titles):
title = valid_titles[answer["options"][0] - 1]
elif "option_identifiers" in answer and len(answer["option_identifiers"]) == 1 and answer["option_identifiers"][0] in valid_titles:
title = answer["option_identifiers"][0]
else:
raise ValidationError("Data field @attendee_name_parts:title requires valid options")
return ('attendee_name_parts', {'title': title})
elif sys_df.startswith("@attendee_name_parts:"):
return ('attendee_name_parts', {sys_df[len("@attendee_name_parts:"):]: answer["answer"]})
else:
return (sys_df[1:], answer["answer"])
else:
return super().run_child_validation(answer)
def to_internal_value(self, data):
result = {}
if 'answers' in data:
answers = super().to_internal_value(data['answers'])
result['answers'] = []
for answer in answers:
if type(answer) is tuple:
k, v = answer
if k == 'attendee_name_parts':
result.setdefault(k, {}).update(v) # merge dicts
else:
result[k] = v
else:
result['answers'].append(answer)
return result
class OrderAnswerListSerializer(ListSerializer):
def update(self, instance, validated_data):
instance.set_answers(validated_data)
class AnswerSerializer(I18nAwareModelSerializer):
question = PrimaryKeyScopedRelatedField(queryset=lambda event, **kw: event.positiondatafields, required=False)
datafield = SlugScopedRelatedField(slug_field='identifier', source='question', queryset=lambda event, **kw: event.positiondatafields, required=False)
question_identifier = serializers.SlugRelatedField(slug_field='identifier', source='question', read_only=True)
option_identifiers = AnswerQuestionOptionsIdentifierField(source='*', required=False)
ignore_extraneous_options_field = False
allow_empty = False
question_identifier = AnswerQuestionIdentifierField(source='*', read_only=True)
option_identifiers = AnswerQuestionOptionsIdentifierField(source='*', read_only=True)
def to_representation(self, instance):
r = super().to_representation(instance)
@@ -397,24 +242,20 @@ class AnswerSerializer(I18nAwareModelSerializer):
'pk': instance.orderposition.pk,
'question': instance.question_id,
}, request=self.context['request'])
elif r['answer'].startswith('file://') and instance.order:
r['answer'] = reverse('api-v1:order-answer', kwargs={
'organizer': instance.order.event.organizer.slug,
'event': instance.order.event.slug,
'code': instance.order.code,
'question': instance.question_id,
}, request=self.context['request'])
return r
class Meta:
model = QuestionAnswer
fields = ('datafield', 'answer', 'options', 'option_identifiers', 'question', 'question_identifier')
fields = ('question', 'answer', 'question_identifier', 'options', 'option_identifiers')
def validate_question(self, q):
if q.event != self.context['event']:
raise ValidationError(
'The specified question does not belong to this event.'
)
return q
def _handle_file_upload(self, data):
data['options'] = []
data.pop('option_identifiers', None)
if self.allow_empty and not data['answer']:
return data
if data['answer'] == 'file:keep':
return data
try:
@@ -429,7 +270,7 @@ class AnswerSerializer(I18nAwareModelSerializer):
pass
elif cf.session_key != get_session_key_for_api_request(self.context["request"]):
raise ValidationError('The submitted file ID "{fid}" was not found.'.format(fid=data['answer']))
except (ValidationError, BaseValidationError, IndexError): # invalid uuid
except (ValidationError, IndexError): # invalid uuid
raise ValidationError('The submitted file ID "{fid}" was not found.'.format(fid=data['answer']))
except CachedFile.DoesNotExist:
raise ValidationError('The submitted file ID "{fid}" was not found.'.format(fid=data['answer']))
@@ -442,52 +283,36 @@ class AnswerSerializer(I18nAwareModelSerializer):
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))
data['options'] = []
data['answer'] = cf.file
return data
def validate(self, data):
if not data.get('question'):
raise ValidationError('Data field not specified.')
raise ValidationError('Question not specified.')
elif data.get('question').type == Question.TYPE_FILE:
return self._handle_file_upload(data)
elif data.get('question').type in (Question.TYPE_CHOICE, Question.TYPE_CHOICE_MULTIPLE):
if not data.get('options') and not data.get("option_identifiers"):
if self.allow_empty:
data['answer'] = None
return data
else:
if not data.get('options'):
raise ValidationError(
'You need to specify options if the question is of a choice type.'
)
if data.get('question').type == Question.TYPE_CHOICE and len(data.get('options')) > 1:
raise ValidationError(
'You can specify at most one option for this question.'
)
for o in data.get('options'):
if o.question_id != data.get('question').pk:
raise ValidationError(
'You need to specify either options or option_identifiers if the data field is of a choice type.'
'The specified option does not belong to this question.'
)
if 'options' in data and "option_identifiers" in data:
raise ValidationError(
'You need to specify either options or option_identifiers, not both.'
)
if data.get('question').type == Question.TYPE_CHOICE and len(data.get('options') or data.get('option_identifiers')) > 1:
raise ValidationError(
'You can specify at most one option for this data field.'
)
if 'options' in data:
for o in data.get('options'):
if o.question_id != data.get('question').pk:
raise ValidationError({
'options': 'The specified option {opt} does not belong to this data field.'.format(opt=o.pk)
})
data['answer'] = ", ".join([str(o) for o in data['options']])
elif 'option_identifiers' in data:
opt_cache = {o.identifier: o for o in data['question'].options.filter(identifier__in=data.get('option_identifiers'))}
for o in data.get('option_identifiers'):
if o not in opt_cache:
raise ValidationError({
'option_identifiers': 'The specified option "{opt}" does not belong to this data field.'.format(opt=o)
})
data['options'] = list(opt_cache.values())
del data['option_identifiers']
data['answer'] = ", ".join([str(o) for o in data['options']])
data['answer'] = ", ".join([str(o) for o in data.get('options')])
else:
if (data.get('options') or data.get('option_identifiers')) and not self.ignore_extraneous_options_field:
if data.get('options'):
raise ValidationError(
'You should not specify options if the data field is not of a choice type.'
'You should not specify options if the question is not of a choice type.'
)
if data.get('question').type == Question.TYPE_BOOLEAN:
@@ -497,7 +322,7 @@ class AnswerSerializer(I18nAwareModelSerializer):
data['answer'] = 'False'
else:
raise ValidationError(
'Please specify "true" or "false" for boolean data fields.'
'Please specify "true" or "false" for boolean questions.'
)
elif data.get('question').type == Question.TYPE_NUMBER:
serializers.DecimalField(
@@ -510,34 +335,9 @@ class AnswerSerializer(I18nAwareModelSerializer):
data['answer'] = serializers.TimeField().to_internal_value(data.get('answer'))
elif data.get('question').type == Question.TYPE_DATETIME:
data['answer'] = serializers.DateTimeField().to_internal_value(data.get('answer'))
data.pop('option_identifiers', None)
return data
class OptionalAnswerSerializer(AnswerSerializer):
answer = serializers.CharField(required=False, allow_null=True, allow_blank=True)
allow_empty = True
class NewAnswerSerializer(AnswerSerializer):
question = None
question_identifier = None
class Meta:
model = QuestionAnswer
fields = ('datafield', 'answer', 'options', 'option_identifiers')
class NewOptionalAnswerSerializer(AnswerSerializer):
answer = serializers.CharField(required=False, allow_null=True, allow_blank=True)
allow_empty = True
class OrderAnswerSerializer(NewAnswerSerializer):
datafield = SlugScopedRelatedField(slug_field='identifier', source='question', queryset=lambda event, **kw: event.orderdatafields, required=False)
class InlineCheckinSerializer(I18nAwareModelSerializer):
device_id = serializers.SlugRelatedField(
source='device',
@@ -672,10 +472,7 @@ class PdfDataSerializer(serializers.Field):
return {}
ev = instance.subevent or instance.order.event
with (
language(instance.order.locale, instance.order.event.settings.region),
assert_num_queries(0) if settings.DEBUG else nullcontext(), # PDF vars should not introduce additional queries per-order / per-position!
):
with language(instance.order.locale, instance.order.event.settings.region):
# This needs to have some extra performance improvements to avoid creating hundreds of queries when
# we serialize a list.
@@ -794,7 +591,7 @@ class OrderPositionPluginDataField(serializers.Field):
class OrderPositionSerializer(I18nAwareModelSerializer):
checkins = InlineCheckinSerializer(many=True, read_only=True)
print_logs = PrintLogSerializer(many=True, read_only=True)
answers = MixedAnswerListSerializer(child=AnswerSerializer(), source='*')
answers = AnswerSerializer(many=True)
downloads = PositionDownloadsField(source='*', read_only=True)
order = serializers.SlugRelatedField(slug_field='code', read_only=True)
pdf_data = PdfDataSerializer(source='*', read_only=True)
@@ -895,7 +692,6 @@ class AttendeeNamePartsField(serializers.Field):
class CheckinListOrderPositionSerializer(OrderPositionSerializer):
require_attention = RequireAttentionField(source='*')
answers = AnswerSerializer(many=True)
attendee_name = AttendeeNameField(source='*')
attendee_name_parts = AttendeeNamePartsField(source='*')
order__status = serializers.SlugRelatedField(read_only=True, slug_field='status', source='order')
@@ -925,7 +721,7 @@ class CheckinListOrderPositionSerializer(OrderPositionSerializer):
self.fields['variation'] = InlineItemVariationSerializer(read_only=True, context=self.context)
if 'answers.question' in self.context['expand']:
self.fields['answers'].child.fields['question'] = POSCompatQuestionSerializer(read_only=True) # TODO(questionnaires)
self.fields['answers'].child.fields['question'] = QuestionSerializer(read_only=True)
if 'addons' in self.context['expand']:
# Experimental feature, undocumented on purpose for now in case we need to remove it again
@@ -1079,13 +875,12 @@ class OrderSerializer(I18nAwareModelSerializer):
payment_provider = OrderPaymentTypeField(source='*', read_only=True)
url = OrderURLField(source='*', read_only=True)
customer = serializers.SlugRelatedField(slug_field='identifier', read_only=True)
sales_channel = SlugScopedRelatedField(
sales_channel = serializers.SlugRelatedField(
slug_field='identifier',
queryset=lambda **context: context["organizer"].sales_channels.all() if "organizer" in context else context["event"].organizer.sales_channels.all(),
queryset=SalesChannel.objects.none(),
required=False,
)
plugin_data = OrderPluginDataField(source='*', allow_null=True, read_only=True)
answers = OrderAnswerListSerializer(child=OrderAnswerSerializer())
class Meta:
model = Order
@@ -1095,7 +890,7 @@ class OrderSerializer(I18nAwareModelSerializer):
'payment_provider', 'fees', 'total', 'tax_rounding_mode', 'comment', 'custom_followup_at', 'invoice_address',
'positions', 'downloads', 'checkin_attention', 'checkin_text', 'last_modified', 'payments', 'refunds',
'require_approval', 'sales_channel', 'url', 'customer', 'valid_if_pending', 'api_meta', 'cancellation_date',
'plugin_data', 'answers',
'plugin_data',
)
read_only_fields = (
'code', 'status', 'testmode', 'secret', 'datetime', 'expires', 'payment_date',
@@ -1105,6 +900,10 @@ class OrderSerializer(I18nAwareModelSerializer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if "organizer" in self.context:
self.fields["sales_channel"].queryset = self.context["organizer"].sales_channels.all()
else:
self.fields["sales_channel"].queryset = self.context["event"].organizer.sales_channels.all()
if not self.context['pdf_data']:
self.fields['positions'].child.fields.pop('pdf_data', None)
@@ -1175,10 +974,6 @@ class OrderSerializer(I18nAwareModelSerializer):
except InvoiceAddress.DoesNotExist:
InvoiceAddress.objects.create(order=instance, **iadata)
order_answers = validated_data.pop('answers', None)
if order_answers is not None:
self.fields['answers'].update(instance, order_answers)
for attr, value in validated_data.items():
if attr in update_fields:
setattr(instance, attr, value)
@@ -1202,7 +997,6 @@ class SimulatedOrderPositionSerializer(OrderPositionSerializer):
class SimulatedOrderSerializer(OrderSerializer):
answers = SimulatedAnswerSerializer(many=True)
positions = SimulatedOrderPositionSerializer(many=True, read_only=True)
@@ -1247,7 +1041,7 @@ class OrderFeeCreateSerializer(I18nAwareModelSerializer):
class OrderPositionCreateSerializer(I18nAwareModelSerializer):
answers = MixedAnswerListSerializer(child=AnswerCreateSerializer(required=False), source='*', required=False)
answers = AnswerCreateSerializer(many=True, required=False)
addon_to = serializers.IntegerField(required=False, allow_null=True)
secret = serializers.CharField(required=False)
attendee_name = serializers.CharField(required=False, allow_null=True)
@@ -1424,7 +1218,6 @@ class OrderCreateSerializer(I18nAwareModelSerializer):
tax_rounding_mode = serializers.ChoiceField(choices=ROUNDING_MODES, allow_null=True, required=False,)
locale = serializers.ChoiceField(choices=[], required=False, allow_null=True)
use_gift_cards = serializers.ListField(child=serializers.CharField(required=False), required=False)
answers = OrderAnswerListSerializer(child=OrderAnswerSerializer(required=False), required=False)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@@ -1440,8 +1233,7 @@ class OrderCreateSerializer(I18nAwareModelSerializer):
fields = ('code', 'status', 'testmode', 'email', 'phone', 'locale', 'payment_provider', 'fees', 'comment', 'sales_channel',
'invoice_address', 'positions', 'checkin_attention', 'checkin_text', 'payment_info', 'payment_date',
'consume_carts', 'force', 'send_email', 'simulate', 'customer', 'custom_followup_at',
'require_approval', 'valid_if_pending', 'expires', 'api_meta', 'tax_rounding_mode', 'use_gift_cards',
'answers',)
'require_approval', 'valid_if_pending', 'expires', 'api_meta', 'tax_rounding_mode', 'use_gift_cards')
def validate_payment_provider(self, pp):
if pp is None:
@@ -1537,7 +1329,6 @@ class OrderCreateSerializer(I18nAwareModelSerializer):
force = validated_data.pop('force', False)
simulate = validated_data.pop('simulate', False)
gift_card_secrets = validated_data.pop('use_gift_cards') if 'use_gift_cards' in validated_data else []
order_answers = validated_data.pop('answers', None)
if (payment_provider is not None or payment_info != '{}') and len(gift_card_secrets) > 0:
raise ValidationError({"use_gift_cards": ['The attribute use_gift_cards is not compatible with payment_provider or payment_info']})
@@ -1800,17 +1591,6 @@ class OrderCreateSerializer(I18nAwareModelSerializer):
order.invoice_address = ia
ia.last_modified = now()
if simulate:
answers = []
for answ_data in (order_answers or []):
options = answ_data.pop('options', [])
answ = WrappedModel(QuestionAnswer(**answ_data))
answ.options = WrappedList(options)
answers.append(answ)
order.answers = answers
elif order_answers is not None:
self.fields['answers'].update(order, order_answers)
# Generate position objects
pos_map = {}
for pos_data in positions_data:
@@ -1915,12 +1695,24 @@ class OrderCreateSerializer(I18nAwareModelSerializer):
if pos.voucher:
Voucher.objects.filter(pk=pos.voucher.pk).update(redeemed=F('redeemed') + 1)
pos.save()
seen_answers = set()
for answ_data in answers_data:
# Workaround for a pretixPOS bug :-(
if answ_data.get('question') in seen_answers:
continue
seen_answers.add(answ_data.get('question'))
pos.set_answers(
answers_data,
ignore_duplicates=True, # Workaround for a pretixPOS bug :-(
answercache=dict()
)
options = answ_data.pop('options', [])
if isinstance(answ_data['answer'], File):
an = answ_data.pop('answer')
answ = pos.answers.create(**answ_data, answer='')
answ.file.save(os.path.basename(an.name), an, save=False)
answ.answer = 'file://' + answ.file.name
answ.save()
else:
answ = pos.answers.create(**answ_data)
answ.options.add(*options)
if use_reusable_medium:
if pos.item.media_policy not in (Item.MEDIA_POLICY_APPEND, Item.MEDIA_POLICY_APPEND_OR_NEW):
+40 -9
View File
@@ -20,17 +20,17 @@
# <https://www.gnu.org/licenses/>.
#
import logging
import os
import pycountry
from django.core.exceptions import ValidationError as DjangoValidationError
from django.core.files import File
from django.core.validators import RegexValidator
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from pretix.api.serializers.order import (
AnswerCreateSerializer, AnswerSerializer, CompatibleCountryField,
MixedAnswerListSerializer, OrderFeeCreateSerializer,
OrderPositionCreateSerializer,
OrderFeeCreateSerializer, OrderPositionCreateSerializer,
)
from pretix.base.models import ItemVariation, Order, OrderFee, OrderPosition
from pretix.base.services.orders import OrderChangeManager, OrderError
@@ -41,7 +41,7 @@ logger = logging.getLogger(__name__)
class OrderPositionCreateForExistingOrderSerializer(OrderPositionCreateSerializer):
order = serializers.SlugRelatedField(slug_field='code', queryset=Order.objects.none(), required=True, allow_null=False)
answers = MixedAnswerListSerializer(child=AnswerCreateSerializer(required=False), source='*', required=False)
answers = AnswerCreateSerializer(many=True, required=False)
addon_to = serializers.IntegerField(required=False, allow_null=True)
secret = serializers.CharField(required=False)
attendee_name = serializers.CharField(required=False, allow_null=True)
@@ -154,7 +154,7 @@ class OrderFeeCreateForExistingOrderSerializer(OrderFeeCreateSerializer):
class OrderPositionInfoPatchSerializer(serializers.ModelSerializer):
answers = MixedAnswerListSerializer(child=AnswerSerializer(), source='*')
answers = AnswerSerializer(many=True)
country = CompatibleCountryField(source='*')
attendee_name = serializers.CharField(required=False)
@@ -207,10 +207,41 @@ class OrderPositionInfoPatchSerializer(serializers.ModelSerializer):
instance.save(update_fields=list(validated_data.keys()))
if answers_data is not None:
try:
instance.set_answers(answers_data)
except DjangoValidationError as e:
raise ValidationError(str(e))
qs_seen = set()
answercache = {
a.question_id: a for a in instance.answers.all()
}
for answ_data in answers_data:
if not answ_data.get('answer'):
continue
options = answ_data.pop('options', [])
if answ_data['question'].pk in qs_seen:
raise ValidationError(f'Question {answ_data["question"]} was sent twice.')
if answ_data['question'].pk in answercache:
a = answercache[answ_data['question'].pk]
if isinstance(answ_data.get('answer'), File):
a.file.save(answ_data['answer'].name, answ_data['answer'], save=False)
a.answer = 'file://' + a.file.name
elif a.answer.startswith('file://') and answ_data['answer'] == "file:keep":
pass # keep current file
else:
for attr, value in answ_data.items():
setattr(a, attr, value)
a.save()
else:
if isinstance(answ_data.get('answer'), File):
an = answ_data.pop('answer')
a = instance.answers.create(**answ_data, answer='')
a.file.save(os.path.basename(an.name), an, save=False)
a.answer = 'file://' + a.file.name
a.save()
else:
a = instance.answers.create(**answ_data)
a.options.set(options)
qs_seen.add(a.question_id)
for qid, a in answercache.items():
if qid not in qs_seen:
a.delete()
return instance
+1 -8
View File
@@ -26,7 +26,6 @@ from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db import transaction
from django.db.models import Q
from django.templatetags.static import static
from django.utils.crypto import get_random_string
from django.utils.translation import gettext, gettext_lazy as _
from i18nfield.rest_framework import I18nField
@@ -220,12 +219,10 @@ class FlexibleTicketRelatedField(serializers.PrimaryKeyRelatedField):
class SalesChannelSerializer(I18nAwareModelSerializer):
type = serializers.CharField(default="api")
icon_url = serializers.SerializerMethodField()
class Meta:
model = SalesChannel
fields = ('identifier', 'type', 'label', 'position', 'icon', 'icon_url')
read_only_fields = ('icon',)
fields = ('identifier', 'type', 'label', 'position')
def validate_type(self, value):
if (not self.instance or not self.instance.pk) and value != "api":
@@ -249,10 +246,6 @@ class SalesChannelSerializer(I18nAwareModelSerializer):
)
return value
def get_icon_url(self, instance):
if '.' in instance.icon:
return static(instance.icon)
class GiftCardSerializer(I18nAwareModelSerializer):
value = serializers.DecimalField(max_digits=13, decimal_places=2, min_value=Decimal('0.00'))
+4 -14
View File
@@ -80,10 +80,7 @@ event_router.register(r'subevents', event.SubEventViewSet)
event_router.register(r'clone', event.CloneEventViewSet)
event_router.register(r'items', item.ItemViewSet)
event_router.register(r'categories', item.ItemCategoryViewSet)
event_router.register(r'questions', item.CompatQuestionViewSet, basename='compatquestion')
event_router.register(r'datafields/position', item.PositionDatafieldViewSet, basename='positiondatafield')
event_router.register(r'datafields/order', item.OrderDatafieldViewSet, basename='orderdatafield')
event_router.register(r'questionnaires', item.QuestionnaireViewSet)
event_router.register(r'questions', item.QuestionViewSet)
event_router.register(r'discounts', discount.DiscountViewSet)
event_router.register(r'quotas', item.QuotaViewSet)
event_router.register(r'vouchers', voucher.VoucherViewSet)
@@ -110,11 +107,8 @@ subevent_router.register(r'seats', event.SeatViewSet)
checkinlist_router = routers.DefaultRouter()
checkinlist_router.register(r'positions', checkin.CheckinListPositionViewSet, basename='checkinlistpos')
orderdatafield_router = routers.DefaultRouter()
orderdatafield_router.register(r'options', item.OrderDatafieldOptionViewSet)
positiondatafield_router = routers.DefaultRouter()
positiondatafield_router.register(r'options', item.PositionDatafieldOptionViewSet)
question_router = routers.DefaultRouter()
question_router.register(r'options', item.QuestionOptionViewSet)
item_router = routers.DefaultRouter()
item_router.register(r'variations', item.ItemVariationViewSet)
@@ -154,11 +148,7 @@ urlpatterns = [
re_path(r'^organizers/(?P<organizer>[^/]+)/teams/(?P<team>[^/]+)/', include(team_router.urls)),
re_path(r'^organizers/(?P<organizer>[^/]+)/events/(?P<event>[^/]+)/items/(?P<item>[^/]+)/', include(item_router.urls)),
re_path(r'^organizers/(?P<organizer>[^/]+)/events/(?P<event>[^/]+)/questions/(?P<question>[^/]+)/',
include(positiondatafield_router.urls)),
re_path(r'^organizers/(?P<organizer>[^/]+)/events/(?P<event>[^/]+)/datafields/order/(?P<question>[^/]+)/',
include(orderdatafield_router.urls)),
re_path(r'^organizers/(?P<organizer>[^/]+)/events/(?P<event>[^/]+)/datafields/position/(?P<question>[^/]+)/',
include(positiondatafield_router.urls)),
include(question_router.urls)),
re_path(r'^organizers/(?P<organizer>[^/]+)/events/(?P<event>[^/]+)/checkinlists/(?P<list>[^/]+)/',
include(checkinlist_router.urls)),
re_path(r'^organizers/(?P<organizer>[^/]+)/events/(?P<event>[^/]+)/orders/(?P<order>[^/]+)/', include(order_router.urls)),
+52 -54
View File
@@ -24,6 +24,8 @@ from datetime import timedelta
from functools import reduce
import django_filters
from django.conf import settings
from django.core.exceptions import ValidationError as BaseValidationError
from django.db import connection, transaction
from django.db.models import (
Count, Exists, F, Max, OrderBy, OuterRef, Prefetch, Q, Subquery,
@@ -48,29 +50,28 @@ from rest_framework.generics import ListAPIView
from rest_framework.permissions import SAFE_METHODS
from rest_framework.response import Response
from pretix.api.compat import get_partial_validation_result
from pretix.api.auth.utils import get_session_key_for_api_auth
from pretix.api.serializers.checkin import (
CheckinListSerializer, CheckinRPCAnnulInputSerializer,
CheckinRPCRedeemInputSerializer, MiniCheckinListSerializer,
)
from pretix.api.serializers.item import POSCompatQuestionSerializer
from pretix.api.serializers.item import QuestionSerializer
from pretix.api.serializers.order import (
OptionalAnswerSerializer, CheckinListOrderPositionSerializer, CheckinSerializer,
FailedCheckinSerializer, MixedAnswerListSerializer, NewOptionalAnswerSerializer,
CheckinListOrderPositionSerializer, CheckinSerializer,
FailedCheckinSerializer,
)
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,
Question, Questionnaire, QuestionnaireRow, ReusableMedium,
RevokedTicketSecret, TeamAPIToken,
Question, ReusableMedium, RevokedTicketSecret, TeamAPIToken,
)
from pretix.base.models.orders import PrintLog
from pretix.base.permissions import AnyPermissionOf
from pretix.base.services.checkin import (
CheckInError, RequiredMediaExchangeError, RequiredQuestionsError, SQLLogic,
_get_checkin_questions, perform_checkin,
perform_checkin,
)
from pretix.base.services.media import perform_media_exchange
from pretix.base.signals import checkin_annulled
@@ -328,6 +329,35 @@ 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:
@@ -459,7 +489,6 @@ def _redeem_process(*, checkinlists, raw_barcode, answers_data, datetime, force,
'pdf_data': pdf_data and (
user if user and user.is_authenticated else auth
).has_event_permission(request.organizer, event, 'event.orders:read', request),
'preferred_questionnaire_type': Questionnaire.QuestionnaireType.POSITION_CHECKIN,
}
common_checkin_args = dict(
@@ -765,51 +794,21 @@ def _redeem_process(*, checkinlists, raw_barcode, answers_data, datetime, force,
op = op_candidates[0]
common_checkin_args['list'] = list_by_event[op.order.event_id]
# 5. Pre-validate all incoming answers, handle file upload, handle system answers
# 5. Pre-validate all incoming answers, handle file upload
given_answers = {}
given_system_answers = {}
if answers_data:
checkin_questions = op.item._checkin_questions = _get_checkin_questions(op)
if type(answers_data) is dict:
# convert old dict format to new 'list of dicts' format
fields_with_options = {"@attendee_name_parts:salutation", "@attendee_name_parts:title"} | {qc.user_datafield_id for qc in checkin_questions if qc.datafield_type in (Question.TYPE_CHOICE, Question.TYPE_CHOICE_MULTIPLE)}
new_answers_data = []
for k, v in answers_data.items():
v = str(v)
for q in op.item.questions.filter(ask_during_checkin=True):
if str(q.pk) in answers_data:
try:
qid, dfid, sysdf = QuestionnaireRow.uncook_id(k)
except ValueError:
continue
ident = {'datafield': sysdf} if sysdf else {'question': k}
if (dfid or sysdf) in fields_with_options:
new_answers_data.append({**ident, 'answer': v, 'option_identifiers': v.split(',') if v else []})
try:
new_answers_data.append({**ident, 'answer': v, 'options': [int(id) for id in v.split(',')]})
except ValueError:
pass
else:
new_answers_data.append({**ident, 'answer': v})
answers_data = new_answers_data
child_serializer = OptionalAnswerSerializer()
child_serializer.ignore_extraneous_options_field = False
else:
child_serializer = NewOptionalAnswerSerializer()
allowed_datafields = {qc.system_datafield or qc.user_datafield_id for qc in checkin_questions if qc.system_datafield or qc.user_datafield_id}
answers_data, errors = get_partial_validation_result(
answers_data,
MixedAnswerListSerializer,
prepare_data=lambda d: {'answers': d},
context={'event': op.order.event, 'request': request, 'allowed_datafields': allowed_datafields},
child=child_serializer
)
given_answers = answers_data.pop('answers', [])
given_system_answers = answers_data
print("errors: ", errors)
print("answers_data: ", answers_data)
print("given_answers: ", given_answers)
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)
else:
given_answers[q] = None
else:
given_answers[q] = q.clean_answer(answers_data[str(q.pk)])
except (ValidationError, BaseValidationError):
pass
# 6. Pass to our actual check-in logic
if use_order_locale:
@@ -829,7 +828,6 @@ def _redeem_process(*, checkinlists, raw_barcode, answers_data, datetime, force,
op=op,
clist=list_by_event[op.order.event_id],
given_answers=given_answers,
given_system_answers=given_system_answers,
force=force,
ignore_unpaid=ignore_unpaid,
nonce=nonce,
@@ -869,13 +867,14 @@ def _redeem_process(*, checkinlists, raw_barcode, answers_data, datetime, force,
else:
perform_checkin(**checkin_args)
except RequiredQuestionsError as e:
qs = POSCompatQuestionSerializer(context={'event': op.order.event})
return Response({
'status': 'incomplete',
'require_attention': op.require_checkin_attention,
'checkin_texts': op.checkin_texts,
'position': CheckinListOrderPositionSerializer(op, context=_make_context(context, op.order.event)).data,
'questions': POSCompatQuestionSerializer.mangle_results(op.order.event, (qs.to_representation(q) for q in e.questionnaire_rows)), # TODO(questionnaires)
'questions': [
QuestionSerializer(q).data for q in e.questions
],
'list': MiniCheckinListSerializer(list_by_event[op.order.event_id]).data,
}, status=400)
except RequiredMediaExchangeError as e:
@@ -974,7 +973,6 @@ class CheckinListPositionViewSet(viewsets.ReadOnlyModelViewSet):
ctx['event'] = self.request.event
ctx['expand'] = self.request.query_params.getlist('expand')
ctx['pdf_data'] = self.request.query_params.get('pdf_data', 'false').lower() == 'true'
ctx['preferred_questionnaire_type'] = Questionnaire.QuestionnaireType.POSITION_CHECKIN
return ctx
def get_filterset_kwargs(self):
+24 -380
View File
@@ -32,43 +32,33 @@
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under the License.
import logging
from typing import Mapping
import django_filters
from django.db import transaction
from django.db.models import Q, Prefetch
from django.db.models.expressions import Exists, OuterRef
from django.db.models import Q
from django.shortcuts import get_object_or_404
from django.utils.functional import cached_property
from django_filters.rest_framework import DjangoFilterBackend, FilterSet
from django_scopes import scopes_disabled
from rest_framework import generics, viewsets
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import PermissionDenied, ValidationError
from rest_framework.response import Response
from pretix.api.exceptions import CompatException
from pretix.api.pagination import TotalOrderingFilter
from pretix.api.serializers.item import (
CompatQuestionSerializer, DatafieldSerializer, ItemAddOnSerializer,
ItemBundleSerializer, ItemCategorySerializer, ItemProgramTimeSerializer,
ItemSerializer, ItemVariationSerializer, POSCompatQuestionSerializer,
QuestionFormSerializer, QuestionnaireSerializer, QuestionOptionSerializer, QuotaSerializer,
ItemAddOnSerializer, ItemBundleSerializer, ItemCategorySerializer,
ItemProgramTimeSerializer, ItemSerializer, ItemVariationSerializer,
QuestionOptionSerializer, QuestionSerializer, QuotaSerializer,
)
from pretix.api.views import ConditionalListView
from pretix.base.models import (
CartPosition, Device, Item, ItemAddOn, ItemBundle, ItemCategory,
ItemProgramTime, ItemVariation, Question, QuestionOption, Quota,
CartPosition, Item, ItemAddOn, ItemBundle, ItemCategory, ItemProgramTime,
ItemVariation, Question, QuestionOption, Quota,
)
from pretix.base.models.items import Questionnaire, QuestionnaireRow
from pretix.base.services.quotas import QuotaAvailability
from pretix.helpers.dicts import merge_dicts
from pretix.helpers.i18n import i18ncomp
logger = logging.getLogger(__name__)
with scopes_disabled():
class ItemFilter(FilterSet):
tax_rate = django_filters.CharFilter(method='tax_rate_qs')
@@ -117,12 +107,7 @@ class ItemViewSet(ConditionalListView, viewsets.ModelViewSet):
'variations', 'addons', 'bundles', 'meta_values', 'meta_values__property',
'variations__meta_values', 'variations__meta_values__property',
'require_membership_types', 'variations__require_membership_types',
'limit_sales_channels', 'variations__limit_sales_channels', 'program_times',
Prefetch('questionnaires', Questionnaire.objects.annotate(
has_attendee_data=Exists(QuestionnaireRow.objects.filter(
questionnaire=OuterRef('pk'), system_datafield__in=('@attendee_name_parts', '@attendee_email')
))
)),
'limit_sales_channels', 'variations__limit_sales_channels', 'program_times'
).all()
@transaction.atomic()
@@ -473,283 +458,27 @@ class ItemCategoryViewSet(ConditionalListView, viewsets.ModelViewSet):
with scopes_disabled():
class DatafieldFilter(FilterSet):
class QuestionFilter(FilterSet):
class Meta:
model = Question
fields = ['identifier']
fields = ['ask_during_checkin', 'required', 'identifier']
class BaseDatafieldViewSet(viewsets.ReadOnlyModelViewSet):
serializer_class = DatafieldSerializer
class QuestionViewSet(ConditionalListView, viewsets.ModelViewSet):
serializer_class = QuestionSerializer
queryset = Question.objects.none()
filter_backends = (DjangoFilterBackend, TotalOrderingFilter)
filterset_class = DatafieldFilter
ordering_fields = ('id')
ordering = ('id')
filterset_class = QuestionFilter
ordering_fields = ('id', 'position')
ordering = ('position', 'id')
permission = None
def get_queryset(self):
return self.request.event.questions.filter(container_type=self.container_type).prefetch_related('options')
def get_object(self):
queryset = self.filter_queryset(self.get_queryset())
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
lookup_value = self.kwargs[lookup_url_kwarg]
try:
numeric_id = int(lookup_value)
except ValueError:
obj = get_object_or_404(queryset, identifier=lookup_value)
else:
qid, dfid, sys_df = QuestionnaireRow.uncook_id(numeric_id)
self.via_questionnaire_id = qid
obj = get_object_or_404(queryset, pk=dfid)
# May raise a permission denied
self.check_object_permissions(self.request, obj)
return obj
def get_serializer_context(self):
ctx = super().get_serializer_context()
ctx['event'] = self.request.event
ctx['container_type'] = self.container_type
return ctx
class BaseWritableDatafieldViewSet(BaseDatafieldViewSet, viewsets.ModelViewSet):
write_permission = 'event.items:write'
@transaction.atomic()
def perform_create(self, serializer):
serializer.save(event=self.request.event)
serializer.instance.log_action(
'pretix.event.question.added',
user=self.request.user,
auth=self.request.auth,
data=self.request.data
)
@transaction.atomic()
def perform_update(self, serializer):
serializer.save(event=self.request.event)
serializer.instance.log_action(
'pretix.event.question.changed',
user=self.request.user,
auth=self.request.auth,
data=self.request.data
)
@transaction.atomic()
def perform_destroy(self, instance):
instance.log_action(
'pretix.event.question.deleted',
user=self.request.user,
auth=self.request.auth,
)
super().perform_destroy(instance)
class PositionDatafieldViewSet(ConditionalListView, BaseWritableDatafieldViewSet):
container_type = Question.ContainerType.ORDERPOSITION
class OrderDatafieldViewSet(ConditionalListView, BaseWritableDatafieldViewSet):
container_type = Question.ContainerType.ORDER
def ordered_union(*lists):
from graphlib import TopologicalSorter
items_set = {item for lst in lists for __ignore, item in lst}
dependencies = {item: set() for item in items_set}
for lst in lists:
for i in range(1, len(lst)):
current_item = lst[i][1]
previous_item = lst[i - 1][1]
dependencies[current_item].add(previous_item)
ts = TopologicalSorter(dependencies)
try:
return list(ts.static_order())
except ValueError:
raise CompatException("Questionnaire configuration incompatible with old data model due to conflicting field orders.")
class DeprecationWarningMixin:
def finalize_response(self, request, response, *args, **kwargs):
if self.deprecation_warning and isinstance(getattr(response, 'data', None), Mapping) and not 'x-deprecated' in response.headers:
response.data = {
'deprecation_warning': self.deprecation_warning,
**response.data
}
response.headers['x-deprecated'] = self.deprecation_warning
return super().finalize_response(request, response, *args, **kwargs)
class CompatListMixin(DeprecationWarningMixin):
deprecation_warning = (
f'This API endpoint is deprecated and will be removed in the future. It only works as long as '
f'your event\'s questionnaire configuration is compatible with the old data model. '
f'Please switch to the .../datafields/ and .../questionnaires/ endpoints.'
)
@property
def ignore_errors(self):
return self.request.query_params.get('ignore_errors', '') == 'true'
def get_serializer_context(self):
ctx = super().get_serializer_context()
ctx['ignore_errors'] = self.ignore_errors
return ctx
def do_the_topo_sort(self, queryset):
products = {}
for df in queryset:
for qc in df.referenced_by.all():
for item_id in qc.questionnaire.items.values_list('pk', flat=True):
k = (qc.questionnaire.type, item_id)
products[k] = products.get(k, []) + [((qc.questionnaire.position, qc.position), df)]
for q in products.values():
q.sort()
try:
result = ordered_union(*products.values())
for i, d in enumerate(result):
d.position = i
except ValueError:
if self.ignore_errors:
pass
else:
raise
return result
def list(self, request, **kwargs):
logger.info('Returning compatible datafield list on %s/%s', request.organizer.slug, request.event.slug)
queryset = self.filter_queryset(self.get_queryset())
queryset = self.do_the_topo_sort(queryset)
serializer = self.get_serializer(queryset, many=True)
resultlist = serializer.data
return Response({
'count': len(resultlist), 'next': None, 'previous': None,
'results': resultlist,
})
with scopes_disabled():
class CompatDatafieldFilter(FilterSet):
ask_during_checkin = django_filters.BooleanFilter(method='ask_during_checkin_qs')
required = django_filters.BooleanFilter(method='required_qs')
class Meta:
model = Question
fields = ['identifier']
def ask_during_checkin_qs(self, qs, name, value):
return qs.filter(
Exists(QuestionnaireRow.objects.filter(
questionnaire__type=Questionnaire.QuestionnaireType.POSITION_CHECKIN if value else Questionnaire.QuestionnaireType.POSITION_PURCHASE,
user_datafield=OuterRef('pk'),
))
)
def required_qs(self, qs, name, value):
cond = Exists(QuestionnaireRow.objects.filter(
required=True,
user_datafield=OuterRef('pk'),
))
if value:
return qs.filter(cond)
else:
return qs.filter(~cond)
class CompatQuestionViewSet(ConditionalListView, CompatListMixin, BaseDatafieldViewSet):
container_type = Question.ContainerType.ORDERPOSITION
serializer_class = CompatQuestionSerializer
filterset_class = CompatDatafieldFilter
pagination_class = None
def get_queryset(self):
return super().get_queryset().prefetch_related('referenced_by', 'referenced_by__questionnaire')
def _check_defer(self, mode, request, *args, **kwargs):
sales_channel_ident = request.query_params.get('sales_channel', None)
if sales_channel_ident is None and isinstance(request.auth, Device):
sales_channel_ident = 'pretixpos' if (request.auth.software_brand or '').startswith('pretixPOS') else 'web'
if sales_channel_ident:
logger.info('Returning app compatible question %s for %s (device: %r %s %s) on %s/%s', mode, sales_channel_ident, request.auth, getattr(request.auth, 'software_brand', ''), getattr(request.auth, 'software_version', ''), request.organizer.slug, request.event.slug)
return POSCompatQuestionViewSet.as_view(
{'get': mode}, sales_channel_ident=sales_channel_ident
)(*self.args, request=request._request, **self.kwargs)
def list(self, request, *args, **kwargs):
if response := self._check_defer('list', request, *args, **kwargs):
return response
logger.info('Returning compatible datafield list on %s/%s', request.organizer.slug, request.event.slug)
return super().list(request, *args, **kwargs)
def retrieve(self, request, *args, **kwargs):
if response := self._check_defer('retrieve', request, *args, **kwargs):
return response
return super().retrieve(request, *args, **kwargs)
class POSCompatQuestionViewSet(DeprecationWarningMixin, viewsets.ReadOnlyModelViewSet):
serializer_class = POSCompatQuestionSerializer
queryset = QuestionnaireRow.objects.none()
permission = None
sales_channel_ident = None
def __init__(self, sales_channel_ident, *args, **kwargs):
self.sales_channel_ident = sales_channel_ident
super().__init__(*args, **kwargs)
@property
def deprecation_warning(self):
return (
f'This API endpoint is deprecated and will be removed in the future. '
f'Results are generated on-the-fly, count and page size may be inaccurate. '
f'Filtered for sales_channel "{self.sales_channel_ident}"'
)
def get_queryset(self):
return QuestionnaireRow.objects.filter(
# only matching sales channel
Q(questionnaire__all_sales_channels=True) | Q(questionnaire__limit_sales_channels__identifier=self.sales_channel_ident),
# only real questions, no text blocks
Q(user_datafield_id__isnull=False) | Q(system_datafield__isnull=False),
questionnaire__event=self.request.event,
# we do legacy compat only for position-level questions
questionnaire__type__startswith='P',
).prefetch_related(
'user_datafield', 'user_datafield__options', 'questionnaire'
).order_by('questionnaire__position', 'position', 'id')
def list(self, request, **kwargs):
resp = super().list(request, **kwargs)
resp.data['results'] = POSCompatQuestionSerializer.mangle_results(self.request.event, resp.data['results'])
return resp
def get_object(self):
queryset = self.filter_queryset(self.get_queryset())
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
qid, dfid, sys_df = QuestionnaireRow.uncook_id(self.kwargs[lookup_url_kwarg])
print(self.kwargs[lookup_url_kwarg], qid, dfid, sys_df)
if qid and sys_df:
obj = get_object_or_404(queryset, questionnaire__pk=qid, system_datafield=sys_df)
elif qid and dfid:
obj = get_object_or_404(queryset, questionnaire__pk=qid, user_datafield__pk=dfid)
else:
obj = get_object_or_404(queryset, user_datafield__pk=dfid)
# May raise a permission denied
self.check_object_permissions(self.request, obj)
return obj
return self.request.event.questions.filter(
# the container_type parameter is undocumented, this API is going to change in a later release
container_type=self.request.GET.get('container_type', Question.ContainerType.ORDERPOSITION),
).prefetch_related('options').all()
@transaction.atomic()
def perform_create(self, serializer):
@@ -786,7 +515,7 @@ class POSCompatQuestionViewSet(DeprecationWarningMixin, viewsets.ReadOnlyModelVi
super().perform_destroy(instance)
class BaseDatafieldOptionViewSet(viewsets.ModelViewSet):
class QuestionOptionViewSet(viewsets.ModelViewSet):
serializer_class = QuestionOptionSerializer
queryset = QuestionOption.objects.none()
filter_backends = (DjangoFilterBackend, TotalOrderingFilter,)
@@ -795,25 +524,19 @@ class BaseDatafieldOptionViewSet(viewsets.ModelViewSet):
permission = None
write_permission = 'event.items:write'
def get_question(self):
return get_object_or_404(
Question,
Q(pk=self.kwargs['question']) | Q(identifier=self.kwargs['question']),
event=self.request.event, container_type=self.container_type,
)
def get_queryset(self):
return self.get_question().options.all()
q = get_object_or_404(Question, pk=self.kwargs['question'], event=self.request.event)
return q.options.all()
def get_serializer_context(self):
ctx = super().get_serializer_context()
ctx['event'] = self.request.event
ctx['question'] = self.get_question()
ctx['question'] = get_object_or_404(Question, pk=self.kwargs['question'], event=self.request.event)
return ctx
@transaction.atomic()
def perform_create(self, serializer):
q = self.get_question()
q = get_object_or_404(Question, pk=self.kwargs['question'], event=self.request.event)
serializer.save(question=q)
q.log_action(
'pretix.event.question.option.added',
@@ -843,85 +566,6 @@ class BaseDatafieldOptionViewSet(viewsets.ModelViewSet):
super().perform_destroy(instance)
class OrderDatafieldOptionViewSet(BaseDatafieldOptionViewSet):
container_type = Question.ContainerType.ORDER
class PositionDatafieldOptionViewSet(BaseDatafieldOptionViewSet):
container_type = Question.ContainerType.ORDERPOSITION
with scopes_disabled():
class QuestionnaireFilter(FilterSet):
sales_channel = django_filters.CharFilter(method='sales_channel_qs')
class Meta:
model = Questionnaire
fields = ['type', 'items', 'sales_channel']
def sales_channel_qs(self, qs, name, value):
return qs.filter(
Q(all_sales_channels=True) | Q(limit_sales_channels__identifier=value)
)
class QuestionnaireViewSet(ConditionalListView, viewsets.ModelViewSet):
serializer_class = QuestionnaireSerializer
queryset = Questionnaire.objects.none()
filter_backends = (DjangoFilterBackend, TotalOrderingFilter)
filterset_class = QuestionnaireFilter
ordering_fields = ('id', 'position')
ordering = ('position', 'id')
permission = None
write_permission = 'event.items:write'
def get_queryset(self):
if 'rows.datafield' in self.request.query_params.getlist('expand'):
prefetch_rows = Prefetch(
'rows',
queryset=QuestionnaireRow.objects.select_related('user_datafield').prefetch_related('user_datafield__options'),
)
else:
prefetch_rows = 'rows'
return self.request.event.questionnaires.prefetch_related(prefetch_rows).all()
def perform_create(self, serializer):
serializer.save(event=self.request.event)
serializer.instance.log_action(
'pretix.event.questionnaire.added',
user=self.request.user,
auth=self.request.auth,
data=self.request.data
)
def get_serializer_context(self):
ctx = super().get_serializer_context()
ctx['event'] = self.request.event
ctx['expand'] = self.request.query_params.getlist('expand')
ctx['expand_name_fields'] = self.request.query_params.get('expand_name_fields', '').lower() == 'true'
return ctx
def perform_update(self, serializer):
if new_type := serializer.validated_data.get('type'):
if new_type.split('_', 1)[0] != serializer.instance.type.split('_', 1)[0]:
raise ValidationError({'type': 'Cannot change container part of type field'})
serializer.save(event=self.request.event)
serializer.instance.log_action(
'pretix.event.questionnaire.changed',
user=self.request.user,
auth=self.request.auth,
data=self.request.data
)
def perform_destroy(self, instance):
instance.log_action(
'pretix.event.questionnaire.deleted',
user=self.request.user,
auth=self.request.auth,
)
super().perform_destroy(instance)
class NumberInFilter(django_filters.BaseInFilter, django_filters.NumberFilter):
pass
+5 -44
View File
@@ -103,7 +103,6 @@ from pretix.base.signals import (
)
from pretix.control.signals import order_search_filter_q
from pretix.helpers import OF_SELF
from pretix.presale.views import prefetch_relevant_questionnaires
logger = logging.getLogger(__name__)
@@ -242,9 +241,7 @@ class OrderViewSetMixin:
qs = qs.select_related('invoice_address')
if 'customer' not in self.request.GET.getlist('exclude'):
qs = qs.select_related('customer')
qs = qs.prefetch_related(
'answers', 'answers__options', 'answers__question', # answers to order-level questions
)
qs = qs.select_related('sales_channel').prefetch_related(self._positions_prefetch(self.request))
return qs
@@ -253,12 +250,6 @@ class OrderViewSetMixin:
opq = OrderPosition.all
else:
opq = OrderPosition.objects
serializer = self.get_serializer()
if ('positions' in serializer.fields and 'answers' in serializer.fields['positions'].child.fields
and serializer.fields['positions'].child.fields['answers'].is_compat_request()):
opq = opq.prefetch_related(
prefetch_relevant_questionnaires(None, None)
)
if request.query_params.get('pdf_data', 'false').lower() == 'true' and getattr(request, 'event', None):
prefetch_related_objects([request.organizer], 'meta_properties')
prefetch_related_objects(
@@ -280,8 +271,7 @@ class OrderViewSetMixin:
Prefetch('meta_values', ItemVariationMetaValue.objects.select_related('property'), to_attr='meta_values_cached')
)),
'answers', 'answers__options', 'answers__question',
# TODO(questionnaires) - add prefetch_relevant_questionnaires (if needed - POS only?)
'item__category', 'item__program_times',
'item__category',
'addon_to__answers', 'addon_to__answers__options', 'addon_to__answers__question',
Prefetch('subevent', queryset=self.request.event.subevents.prefetch_related(
Prefetch('meta_values', to_attr='meta_values_cached', queryset=SubEventMetaValue.objects.select_related('property'))
@@ -297,9 +287,7 @@ class OrderViewSetMixin:
Prefetch('checkins', queryset=Checkin.objects.select_related('device')),
Prefetch('print_logs', queryset=PrintLog.objects.select_related('device')),
'item', 'variation',
Prefetch('answers', queryset=QuestionAnswer.objects.prefetch_related('options', 'question')
# TODO(questionnaires) .order_by('question__position')
),
Prefetch('answers', queryset=QuestionAnswer.objects.prefetch_related('options', 'question').order_by('question__position')),
'seat',
)
)
@@ -718,29 +706,6 @@ class EventOrderViewSet(OrderViewSetMixin, viewsets.ModelViewSet):
status=status.HTTP_400_BAD_REQUEST
)
@action(detail=True, url_name='answer', url_path=r'answer/(?P<question>\d+)')
def answer(self, request, **kwargs):
order = self.get_object()
answer = get_object_or_404(
QuestionAnswer,
order=order,
question_id=kwargs.get('question')
)
if not answer.file:
raise NotFound()
ftype, ignored = mimetypes.guess_type(answer.file.name)
return FileResponse(
answer.file,
filename='{}-{}-{}'.format(
self.request.event.slug.upper(),
order.code,
os.path.basename(answer.file.name).split('.', 1)[1]
),
as_attachment=True,
content_type=ftype or 'application/binary'
)
def create(self, request, *args, **kwargs):
if 'send_mail' in request.data and 'send_email' not in request.data and isinstance(request.data, dict):
request.data['send_email'] = request.data['send_mail']
@@ -1150,7 +1115,7 @@ class OrderPositionViewSetMixin:
)),
'variation',
'answers', 'answers__options', 'answers__question',
'item__category', 'item__program_times',
'item__category',
'addon_to__answers', 'addon_to__answers__options', 'addon_to__answers__question',
Prefetch('addons', qs.select_related('item', 'variation')),
Prefetch('subevent', queryset=self.request.event.subevents.prefetch_related(
@@ -1192,10 +1157,6 @@ class OrderPositionViewSetMixin:
).select_related(
'item', 'order', 'seat'
)
if self.get_serializer().fields['answers'].is_compat_request():
qs = qs.prefetch_related(
prefetch_relevant_questionnaires(None, None)
)
return qs
def _get_output_provider(self, identifier):
@@ -1338,7 +1299,7 @@ class EventOrderPositionViewSet(OrderPositionViewSetMixin, viewsets.ModelViewSet
pos = self.get_object()
answer = get_object_or_404(
QuestionAnswer,
orderposition=pos,
orderposition=self.get_object(),
question_id=kwargs.get('question')
)
if not answer.file:
+32 -35
View File
@@ -28,28 +28,38 @@ from django.utils.translation import gettext_lazy as _, pgettext_lazy
from pretix.base.models import Checkin, InvoiceAddress, Order, Question
from pretix.base.settings import PERSON_NAME_SCHEMES
from pretix.helpers.models import find_first_with_cache
from pretix.multidomain.urlreverse import eventreverse_absolute
def get_position_answer(op, question_identifier=None):
a = find_first_with_cache(op.answers, question__identifier=question_identifier)
def get_answer(op, question_identifier=None):
a = None
if op.addon_to:
if "answers" in getattr(op.addon_to, "_prefetched_objects_cache", {}):
try:
a = [
a
for a in op.addon_to.answers.all()
if a.question.identifier == question_identifier
][0]
except IndexError:
pass
else:
a = op.addon_to.answers.filter(
question__identifier=question_identifier
).first()
if a is None and op.addon_to:
a = find_first_with_cache(op.addon_to.answers, question__identifier=question_identifier)
if not a:
return ""
if "answers" in getattr(op, "_prefetched_objects_cache", {}):
try:
a = [
a
for a in op.answers.all()
if a.question.identifier == question_identifier
][0]
except IndexError:
pass
else:
if a.question.type in (Question.TYPE_CHOICE, Question.TYPE_CHOICE_MULTIPLE):
return [str(o.identifier) for o in a.options.all()]
if a.question.type == Question.TYPE_BOOLEAN:
return a.answer == "True"
return a.answer
a = op.answers.filter(question__identifier=question_identifier).first()
def get_order_answer(order, question_identifier=None):
a = find_first_with_cache(order.answers, question__identifier=question_identifier)
if not a:
return ""
else:
@@ -117,11 +127,10 @@ DataFieldCategory = namedtuple(
CAT_ORDER_POSITION = DataFieldCategory(10, _('Order position details'))
CAT_ATTENDEE = DataFieldCategory(11, _('Attendee details'))
CAT_ORDER_POSITION_DATAFIELDS = DataFieldCategory(12, _('Order position data fields'))
CAT_QUESTIONS = DataFieldCategory(12, _('Questions'))
CAT_PRODUCT = DataFieldCategory(20, _('Product details'))
CAT_ORDER = DataFieldCategory(21, _('Order details'))
CAT_ORDER_DATAFIELDS = DataFieldCategory(22, _('Order data fields'))
CAT_INVOICE_ADDRESS = DataFieldCategory(23, _('Invoice address'))
CAT_INVOICE_ADDRESS = DataFieldCategory(22, _('Invoice address'))
CAT_EVENT = DataFieldCategory(30, _('Event information'))
CAT_EVENT_OR_SUBEVENT = DataFieldCategory(31, pgettext_lazy('subevent', 'Event or date information'))
@@ -576,26 +585,14 @@ def get_data_fields(event, for_model=None):
+ [
DataFieldInfo(
ORDER_POSITION,
CAT_ORDER_POSITION_DATAFIELDS,
CAT_QUESTIONS,
"question_" + q.identifier,
_("Data field: {name}").format(name=str(q.internal_name)),
_("Question: {name}").format(name=str(q.question)),
q.type,
get_enum_opts(q),
partial(lambda qq, position: get_position_answer(position, qq.identifier), q),
partial(lambda qq, position: get_answer(position, qq.identifier), q),
)
for q in event.positiondatafields.filter(~Q(type=Question.TYPE_FILE)).prefetch_related("options")
]
+ [
DataFieldInfo(
ORDER,
CAT_ORDER_DATAFIELDS,
"orderdatafield_" + q.identifier,
_("Order data field: {name}").format(name=str(q.internal_name)),
q.type,
get_enum_opts(q),
partial(lambda qq, order: get_order_answer(order, qq.identifier), q),
)
for q in event.orderdatafields.filter(~Q(type=Question.TYPE_FILE)).prefetch_related("options")
for q in event.questions.filter(~Q(type=Question.TYPE_FILE)).prefetch_related("options")
]
)
if not any(field_name == "given_name" for field_name, label, weight in name_scheme["fields"]):
+1 -1
View File
@@ -62,7 +62,7 @@ class AnswerFilesExporter(BaseExporter):
[
('questions',
forms.ModelMultipleChoiceField(
queryset=self.event.positiondatafields.filter(type='F'),
queryset=self.event.questions.filter(type='F'),
label=_('Questions'),
widget=forms.CheckboxSelectMultiple(
attrs={'class': 'scrolling-multiple-choice'}
+4 -9
View File
@@ -19,7 +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 django.db.models import Exists, OuterRef, Prefetch
from django.db.models import Prefetch
from django.dispatch import receiver
from django.utils.formats import date_format
from django.utils.translation import gettext_lazy as _, pgettext_lazy
@@ -28,7 +28,7 @@ from openpyxl.utils import get_column_letter
from ...helpers.safe_openpyxl import SafeCell
from ..exporter import ListExporter
from ..models import ItemMetaValue, ItemVariation, ItemVariationMetaValue, Questionnaire, QuestionnaireRow
from ..models import ItemMetaValue, ItemVariation, ItemVariationMetaValue
from ..signals import register_data_exporters
@@ -124,11 +124,6 @@ class ItemDataExporter(ListExporter):
),
),
),
Prefetch('questionnaires', Questionnaire.objects.annotate(
has_attendee_data=Exists(QuestionnaireRow.objects.filter(
questionnaire=OuterRef('pk'), system_datafield__in=('@attendee_name_parts', '@attendee_email')
))
)),
).select_related('category', 'tax_rule'):
vars = list(i.variations.all())
@@ -158,7 +153,7 @@ class ItemDataExporter(ListExporter):
_("Yes") if i.free_price else "",
str(i.tax_rule) if i.tax_rule else "",
_("Yes") if i.admission else "",
_("Yes") if any(q.has_attendee_data for q in i.questionnaires.all()) else "",
_("Yes") if i.personalized else "",
_("Yes") if i.generate_tickets else (_("Default") if i.generate_tickets is None else ""),
_("Yes") if i.allow_waitinglist else "",
date_format(_max(i.available_from, v.available_from).astimezone(self.timezone),
@@ -206,7 +201,7 @@ class ItemDataExporter(ListExporter):
_("Yes") if i.free_price else "",
str(i.tax_rule) if i.tax_rule else "",
_("Yes") if i.admission else "",
_("Yes") if any(q.has_attendee_data for q in i.questionnaires.all()) else "",
_("Yes") if i.personalized else "",
_("Yes") if i.generate_tickets else (_("Default") if i.generate_tickets is None else ""),
_("Yes") if i.allow_waitinglist else "",
date_format(i.available_from.astimezone(self.timezone),
+5 -17
View File
@@ -84,6 +84,7 @@ class JSONExporter(BaseExporter):
'tax_rate': item.tax_rule.rate if item.tax_rule else Decimal('0.00'),
'tax_name': str(item.tax_rule.name) if item.tax_rule else None,
'admission': item.admission,
'personalized': item.personalized,
'active': item.active,
'sales_channels': [c.identifier for c in (all_sales_channels if item.all_sales_channels else item.limit_sales_channels.all())],
'description': str(item.description),
@@ -148,26 +149,13 @@ class JSONExporter(BaseExporter):
'id': question.id,
'identifier': question.identifier,
'required': question.required,
'question': str(question.internal_name),
'question': str(question.question),
'position': question.position,
'show_during_checkin': question.show_during_checkin,
'print_on_invoice': question.print_on_invoice,
'hidden': question.hidden,
'ask_during_checkin': question.ask_during_checkin,
'help_text': str(question.help_text),
'type': question.type
} for question in self.event.positiondatafields
],
'orderdatafields': [
{
'id': question.id,
'identifier': question.identifier,
'required': question.required,
'question': str(question.internal_name),
'position': question.position,
'show_during_checkin': question.show_during_checkin,
'print_on_invoice': question.print_on_invoice,
'help_text': str(question.help_text),
'type': question.type
} for question in self.event.orderdatafields
} for question in self.event.questions.all()
],
'orders': [
{
+3 -3
View File
@@ -677,16 +677,16 @@ class OrderListExporter(MultiSheetListExporter):
if form_data['group_multiple_choice']:
for o in q.options.all():
options[q.pk].append(o)
headers.append(str(q.internal_name))
headers.append(str(q.question))
else:
for o in q.options.all():
headers.append(str(q.internal_name) + ' – ' + str(o.answer))
headers.append(str(q.question) + ' – ' + str(o.answer))
options[q.pk].append(o)
else:
if q.type == Question.TYPE_CHOICE:
for o in q.options.all():
options[q.pk].append(o)
headers.append(str(q.internal_name))
headers.append(str(q.question))
headers += [
_('Invoice address company'),
_('Invoice address name'),
+188 -203
View File
@@ -36,6 +36,7 @@ import copy
import json
import logging
import re
from collections import namedtuple
from datetime import timedelta
from decimal import Decimal
from io import BytesIO
@@ -49,13 +50,12 @@ from django.contrib import messages
from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import ProgrammingError
from django.db.models import Prefetch, Q, QuerySet
from django.db.models import QuerySet
from django.forms import Select, widgets
from django.forms.widgets import FILE_INPUT_CONTRADICTION
from django.utils.formats import date_format
from django.utils.functional import lazy
from django.utils.html import escape, format_html
from django.utils.html import escape
from django.utils.safestring import mark_safe
from django.utils.text import format_lazy
from django.utils.timezone import get_current_timezone
@@ -82,10 +82,7 @@ from pretix.base.i18n import (
from pretix.base.invoicing.transmission import (
get_transmission_types, transmission_types,
)
from pretix.base.models import (
InvoiceAddress, Item, Question, Questionnaire, QuestionnaireRow,
QuestionOption,
)
from pretix.base.models import InvoiceAddress, Item, Question, QuestionOption
from pretix.base.models.tax import ask_for_vat_id
from pretix.base.services.tax import (
VATIDFinalError, VATIDTemporaryError, normalize_vat_id, validate_vat_id,
@@ -650,22 +647,49 @@ class PortraitImageField(SizeValidationMixin, ExtValidationMixin, forms.FileFiel
super().__init__(*args, **kwargs)
FakeQuestion = namedtuple(
'FakeQuestion', 'id question position required help_text container_type', defaults=('', Question.ContainerType.ORDERPOSITION)
)
def get_fake_attendee_questions(settings):
fq = []
sqo = settings.system_question_order
if settings.attendee_names_asked:
fq.append(FakeQuestion('attendee_name_parts', _('Attendee name'), sqo.get('attendee_name_parts', 0), settings.attendee_names_required))
if settings.attendee_emails_asked:
fq.append(FakeQuestion('attendee_email', _('Attendee email'), sqo.get('attendee_email', 0), settings.attendee_emails_required))
if settings.attendee_company_asked:
fq.append(FakeQuestion('company', _('Company'), sqo.get('company', 0), settings.attendee_company_required))
if settings.attendee_addresses_asked:
fq.append(FakeQuestion('street', _('Street'), sqo.get('street', 0), settings.attendee_addresses_required))
fq.append(FakeQuestion('zipcode', _('ZIP code'), sqo.get('zipcode', 0), settings.attendee_addresses_required))
fq.append(FakeQuestion('city', _('City'), sqo.get('city', 0), settings.attendee_addresses_required))
fq.append(FakeQuestion('state', _('State'), sqo.get('country', 0), settings.attendee_addresses_required))
fq.append(FakeQuestion('country', _('Country'), sqo.get('country', 0), settings.attendee_addresses_required))
return fq
class BaseQuestionsForm(forms.Form):
"""
This is the base form class responsible for asking order- or ticket-related questions.
"""
address_validation = False
def build_user_question_field(self, request, event, answerlist, qc, datafield):
def build_user_question_field(self, request, event, answerlist, q):
# Do we already have an answer? Provide it as the initial value
answers = [a for a in answerlist if a.question_id == datafield.id]
answers = [a for a in answerlist if a.question_id == q.id]
if answers:
initial = answers[0]
else:
initial = None
tz = ZoneInfo(event.settings.timezone)
required = qc.required and not self.all_optional
if datafield.type == Question.TYPE_BOOLEAN:
required = q.required and not self.all_optional
if q.type == Question.TYPE_BOOLEAN:
if required:
# For some reason, django-bootstrap3 does not set the required attribute
# itself.
@@ -679,105 +703,107 @@ class BaseQuestionsForm(forms.Form):
initialbool = False
field = forms.BooleanField(
label=self.make_label(qc), required=required,
help_text=rich_text(qc.help_text),
label=escape(q.question), required=required,
help_text=rich_text(q.help_text),
initial=initialbool, widget=widget,
)
elif datafield.type == Question.TYPE_NUMBER:
elif q.type == Question.TYPE_NUMBER:
field = forms.DecimalField(
label=self.make_label(qc), required=required,
min_value=datafield.valid_number_min or Decimal('0.00'),
max_value=datafield.valid_number_max,
help_text=rich_text(qc.help_text),
label=escape(q.question), required=required,
min_value=q.valid_number_min or Decimal('0.00'),
max_value=q.valid_number_max,
help_text=rich_text(q.help_text),
initial=initial.answer if initial else None,
)
elif datafield.type == Question.TYPE_STRING:
elif q.type == Question.TYPE_STRING:
field = forms.CharField(
label=self.make_label(qc), required=required,
min_length=datafield.valid_string_length_min,
max_length=datafield.valid_string_length_max,
help_text=rich_text(qc.help_text),
label=escape(q.question), required=required,
min_length=q.valid_string_length_min,
max_length=q.valid_string_length_max,
help_text=rich_text(q.help_text),
initial=initial.answer if initial else None,
)
elif datafield.type == Question.TYPE_TEXT:
elif q.type == Question.TYPE_TEXT:
field = forms.CharField(
label=self.make_label(qc), required=required,
min_length=datafield.valid_string_length_min,
max_length=datafield.valid_string_length_max,
help_text=rich_text(qc.help_text),
label=escape(q.question), required=required,
min_length=q.valid_string_length_min,
max_length=q.valid_string_length_max,
help_text=rich_text(q.help_text),
widget=forms.Textarea,
initial=initial.answer if initial else None,
)
elif datafield.type == Question.TYPE_COUNTRYCODE:
elif q.type == Question.TYPE_COUNTRYCODE:
field = CountryField(
countries=CachedCountries,
blank=True, null=True, blank_label=' ',
).formfield(
label=self.make_label(qc), required=required,
help_text=rich_text(qc.help_text),
label=escape(q.question), required=required,
help_text=rich_text(q.help_text),
widget=forms.Select,
empty_label=' ',
initial=initial.answer if initial else (guess_country_from_request(request, event) if required else None),
initial=initial.answer if initial else (
guess_country_from_request(request, event) if required else None),
)
elif datafield.type == Question.TYPE_CHOICE:
elif q.type == Question.TYPE_CHOICE:
field = forms.ModelChoiceField(
queryset=datafield.options,
label=self.make_label(qc), required=required,
help_text=rich_text(qc.help_text),
queryset=q.options,
label=escape(q.question), required=required,
help_text=rich_text(q.help_text),
widget=forms.Select,
to_field_name='identifier',
empty_label='',
initial=initial.options.first() if initial else None,
)
elif datafield.type == Question.TYPE_CHOICE_MULTIPLE:
elif q.type == Question.TYPE_CHOICE_MULTIPLE:
field = forms.ModelMultipleChoiceField(
queryset=datafield.options,
label=self.make_label(qc), required=required,
help_text=rich_text(qc.help_text),
queryset=q.options,
label=escape(q.question), required=required,
help_text=rich_text(q.help_text),
to_field_name='identifier',
widget=QuestionCheckboxSelectMultiple,
initial=initial.options.all() if initial else None,
)
elif datafield.type == Question.TYPE_FILE:
if datafield.valid_file_portrait:
elif q.type == Question.TYPE_FILE:
if q.valid_file_portrait:
field = PortraitImageField(
label=self.make_label(qc), required=required,
help_text=rich_text(qc.help_text),
label=escape(q.question), required=required,
help_text=rich_text(q.help_text),
initial=initial.file if initial else None,
widget=PortraitImageWidget(answer=initial, request=request, attrs={'data-portrait-photo': 'true'}),
widget=PortraitImageWidget(answer=initial, request=request,
attrs={'data-portrait-photo': 'true'}),
)
else:
field = ExtFileField(
label=self.make_label(qc), required=required,
help_text=rich_text(qc.help_text),
label=escape(q.question), required=required,
help_text=rich_text(q.help_text),
initial=initial.file if initial else None,
widget=UploadedFileWidget(answer=initial, request=request),
ext_whitelist=settings.FILE_UPLOAD_EXTENSIONS_OTHER,
max_size=settings.FILE_UPLOAD_MAX_SIZE_OTHER,
)
elif datafield.type == Question.TYPE_DATE:
elif q.type == Question.TYPE_DATE:
attrs = {}
if datafield.valid_date_min:
attrs['data-min'] = datafield.valid_date_min.isoformat()
if datafield.valid_date_max:
attrs['data-max'] = datafield.valid_date_max.isoformat()
help_text = qc.help_text
if q.valid_date_min:
attrs['data-min'] = q.valid_date_min.isoformat()
if q.valid_date_max:
attrs['data-max'] = q.valid_date_max.isoformat()
help_text = q.help_text
if not help_text:
if datafield.valid_date_min and datafield.valid_date_max:
if q.valid_date_min and q.valid_date_max:
help_text = format_lazy(
_('Please enter a date between {min} and {max}.'),
min=date_format(datafield.valid_date_min, "SHORT_DATE_FORMAT"),
max=date_format(datafield.valid_date_max, "SHORT_DATE_FORMAT"),
min=date_format(q.valid_date_min, "SHORT_DATE_FORMAT"),
max=date_format(q.valid_date_max, "SHORT_DATE_FORMAT"),
)
elif datafield.valid_date_min:
elif q.valid_date_min:
help_text = format_lazy(
_('Please enter a date no earlier than {min}.'),
min=date_format(datafield.valid_date_min, "SHORT_DATE_FORMAT"),
min=date_format(q.valid_date_min, "SHORT_DATE_FORMAT"),
)
elif datafield.valid_date_max:
elif q.valid_date_max:
help_text = format_lazy(
_('Please enter a date no later than {max}.'),
max=date_format(datafield.valid_date_max, "SHORT_DATE_FORMAT"),
max=date_format(q.valid_date_max, "SHORT_DATE_FORMAT"),
)
if initial and initial.answer:
try:
@@ -787,16 +813,16 @@ class BaseQuestionsForm(forms.Form):
else:
_initial = None
field = forms.DateField(
label=self.make_label(qc), required=required,
label=escape(q.question), required=required,
help_text=rich_text(help_text),
initial=_initial,
widget=DatePickerWidget(attrs),
)
if datafield.valid_date_min:
field.validators.append(MinDateValidator(datafield.valid_date_min))
if datafield.valid_date_max:
field.validators.append(MaxDateValidator(datafield.valid_date_max))
elif datafield.type == Question.TYPE_TIME:
if q.valid_date_min:
field.validators.append(MinDateValidator(q.valid_date_min))
if q.valid_date_max:
field.validators.append(MaxDateValidator(q.valid_date_max))
elif q.type == Question.TYPE_TIME:
if initial and initial.answer:
try:
_initial = dateutil.parser.parse(initial.answer).time()
@@ -805,29 +831,29 @@ class BaseQuestionsForm(forms.Form):
else:
_initial = None
field = forms.TimeField(
label=self.make_label(qc), required=required,
help_text=rich_text(qc.help_text),
label=escape(q.question), required=required,
help_text=rich_text(q.help_text),
initial=_initial,
widget=TimePickerWidget(without_seconds=True),
)
elif datafield.type == Question.TYPE_DATETIME:
help_text = qc.help_text
elif q.type == Question.TYPE_DATETIME:
help_text = q.help_text
if not help_text:
if datafield.valid_datetime_min and datafield.valid_datetime_max:
if q.valid_datetime_min and q.valid_datetime_max:
help_text = format_lazy(
_('Please enter a date and time between {min} and {max}.'),
min=date_format(datafield.valid_datetime_min, "SHORT_DATETIME_FORMAT"),
max=date_format(datafield.valid_datetime_max, "SHORT_DATETIME_FORMAT"),
min=date_format(q.valid_datetime_min, "SHORT_DATETIME_FORMAT"),
max=date_format(q.valid_datetime_max, "SHORT_DATETIME_FORMAT"),
)
elif datafield.valid_datetime_min:
elif q.valid_datetime_min:
help_text = format_lazy(
_('Please enter a date and time no earlier than {min}.'),
min=date_format(datafield.valid_datetime_min, "SHORT_DATETIME_FORMAT"),
min=date_format(q.valid_datetime_min, "SHORT_DATETIME_FORMAT"),
)
elif datafield.valid_datetime_max:
elif q.valid_datetime_max:
help_text = format_lazy(
_('Please enter a date and time no later than {max}.'),
max=date_format(datafield.valid_datetime_max, "SHORT_DATETIME_FORMAT"),
max=date_format(q.valid_datetime_max, "SHORT_DATETIME_FORMAT"),
)
if initial and initial.answer:
@@ -839,20 +865,20 @@ class BaseQuestionsForm(forms.Form):
_initial = None
field = SplitDateTimeField(
label=self.make_label(qc), required=required,
label=escape(q.question), required=required,
help_text=rich_text(help_text),
initial=_initial,
widget=SplitDateTimePickerWidget(
time_format=get_format_without_seconds('TIME_INPUT_FORMATS'),
min_date=datafield.valid_datetime_min,
max_date=datafield.valid_datetime_max
min_date=q.valid_datetime_min,
max_date=q.valid_datetime_max
),
)
if datafield.valid_datetime_min:
field.validators.append(MinDateTimeValidator(datafield.valid_datetime_min))
if datafield.valid_datetime_max:
field.validators.append(MaxDateTimeValidator(datafield.valid_datetime_max))
elif datafield.type == Question.TYPE_PHONENUMBER:
if q.valid_datetime_min:
field.validators.append(MinDateTimeValidator(q.valid_datetime_min))
if q.valid_datetime_max:
field.validators.append(MaxDateTimeValidator(q.valid_datetime_max))
elif q.type == Question.TYPE_PHONENUMBER:
if initial:
try:
initial = PhoneNumber().from_string(initial.answer)
@@ -865,96 +891,72 @@ class BaseQuestionsForm(forms.Form):
initial = "+{}.".format(phone_prefix)
field = PhoneNumberField(
label=self.make_label(qc), required=required,
help_text=rich_text(qc.help_text),
label=escape(q.question), required=required,
help_text=rich_text(q.help_text),
# We now exploit an implementation detail in PhoneNumberPrefixWidget to allow us to pass just
# a country code but no number as an initial value. It's a bit hacky, but should be stable for
# the future.
initial=initial,
widget=WrappedPhoneNumberPrefixWidget()
)
else:
raise ProgrammingError('Invalid question type')
field.datafield = datafield
field.questionnaire_row = qc
field.question = q
if answers:
# Cache the answer object for later use
field.answer_object = answers[0]
field.answer = answers[0]
if qc.dependency_question_id:
field.widget.attrs['data-question-dependency'] = qc.dependency_question.form_field_name
field.widget.attrs['data-question-dependency-values'] = escapejson_attr(json.dumps(qc.dependency_values))
if datafield.type != 'M':
field.widget.attrs['required'] = qc.required and not self.all_optional
field._required = qc.required and not self.all_optional
if q.dependency_question_id:
field.widget.attrs['data-question-dependency'] = q.dependency_question_id
field.widget.attrs['data-question-dependency-values'] = escapejson_attr(json.dumps(q.dependency_values))
if q.type != 'M':
field.widget.attrs['required'] = q.required and not self.all_optional
field._required = q.required and not self.all_optional
field.required = False
return field
def build_text_block(self, request, event, qc):
return forms.CharField( # TODO(questionnaires): use a less hacky way to format this field
required=False,
label="",
help_text=rich_text((f"#### {qc.label}\n" if qc.label else "") + str(qc.help_text)),
disabled=True,
widget=QuestionCheckboxSelectMultiple,
)
def check_user_questions(self, d):
question_cache = {f.question.pk: f.question for f in self.fields.values() if getattr(f, 'question', None)}
def make_label(self, qc):
label = escape(qc.label)
if qc.questionnaire.ask_during_checkin:
label += format_html(' <span class="fa fa-qrcode text-primary" data-toggle="tooltip" title="{}"></span>', _("This question will be asked during check-in."))
if qc.questionnaire.hidden:
label += format_html(' <span class="fa fa-eye-slash text-primary" data-toggle="tooltip" title="{}"></span>', _("Hidden question"))
return label
def check_user_questions(self, formdata):
row_cache = {f.questionnaire_row.pk: f.questionnaire_row for f in self.fields.values() if getattr(f, 'questionnaire_row', None)}
user_fields = [f for f in self.fields.values() if getattr(f, 'datafield', None)]
def question_is_visible(parentid, expectedvals):
if parentid is None:
return True
if parentid not in row_cache:
def question_is_visible(parentid, qvals):
if parentid not in question_cache:
return False
parentq = row_cache[parentid]
if not question_is_visible(parentq.dependency_question_id, parentq.dependency_values):
parentq = question_cache[parentid]
if parentq.dependency_question_id and not question_is_visible(parentq.dependency_question_id, parentq.dependency_values):
return False
if parentq.form_field_name not in formdata:
if 'question_%d' % parentid not in d:
return False
formval = formdata.get(parentq.form_field_name)
dval = d.get('question_%d' % parentid)
return (
('True' in expectedvals and formval)
or ('False' in expectedvals and not formval)
or (isinstance(formval, QuestionOption) and formval.identifier in expectedvals)
or (isinstance(formval, (list, QuerySet)) and any(qval in [o.identifier for o in formval] for qval in expectedvals))
('True' in qvals and dval)
or ('False' in qvals and not dval)
or (isinstance(dval, QuestionOption) and dval.identifier in qvals)
or (isinstance(dval, (list, QuerySet)) and any(qval in [o.identifier for o in dval] for qval in qvals))
)
def question_is_required(qr):
return qr.required and question_is_visible(qr.dependency_question_id, qr.dependency_values)
def question_is_required(q):
return (
q.required and
(not q.dependency_question_id or question_is_visible(q.dependency_question_id, q.dependency_values))
)
if not self.all_optional:
for field in user_fields:
qr = field.questionnaire_row
answer = formdata.get(qr.form_field_name)
field = self[qr.form_field_name]
if question_is_required(qr) and not answer and answer != 0 and not field.errors:
raise ValidationError({qr.form_field_name: [_('This field is required.')]})
for q in question_cache.values():
answer = d.get('question_%d' % q.pk)
field = self['question_%d' % q.pk]
if question_is_required(q) and not answer and answer != 0 and not field.errors:
raise ValidationError({'question_%d' % q.pk: [_('This field is required.')]})
# Strip invisible question from cleaned_data so they don't end up in the database
for field in user_fields:
qr = field.questionnaire_row
answer = formdata.get(qr.form_field_name)
if not question_is_visible(qr.dependency_question_id, qr.dependency_values) and answer is not None:
formdata[qr.form_field_name] = None
for q in question_cache.values():
answer = d.get('question_%d' % q.pk)
if q.dependency_question_id and not question_is_visible(q.dependency_question_id, q.dependency_values) and answer is not None:
d['question_%d' % q.pk] = None
# Strip False answers to required yes/no questions even if all_optional is set, as our data model assumes that
# required yes/no questions can only be answered with yes
for field in user_fields:
qr = field.questionnaire_row
if qr.required and field.datafield.type == Question.TYPE_BOOLEAN:
if qr.form_field_name in formdata and formdata[qr.form_field_name] is False:
formdata[qr.form_field_name] = None
for q in question_cache.values():
if q.required and q.type == Question.TYPE_BOOLEAN:
if 'question_%d' % q.pk in d and d['question_%d' % q.pk] is False:
d['question_%d' % q.pk] = None
class OrderLevelQuestionsForm(BaseQuestionsForm):
@@ -962,7 +964,8 @@ class OrderLevelQuestionsForm(BaseQuestionsForm):
"""
Takes two additional keyword arguments:
:param container: The checkout session or order the form should be for
:param checkoutsession: The checkout session the form should be for
:param order: The order the form should be for
:param event: The event this belongs to
"""
request = kwargs.pop('request', None)
@@ -971,34 +974,14 @@ class OrderLevelQuestionsForm(BaseQuestionsForm):
super().__init__(*args, **kwargs)
questionnaires = Questionnaire.objects.filter(
Q(all_sales_channels=True) | Q(limit_sales_channels__identifier=container.sales_channel.identifier),
event=event, type=Questionnaire.QuestionnaireType.ORDER_PURCHASE,
).order_by('position').prefetch_related(
Prefetch('rows', QuestionnaireRow.objects.prefetch_related(
Prefetch('user_datafield', Question.objects.prefetch_related(
Prefetch('options', QuestionOption.objects.prefetch_related(Prefetch(
# This prefetch statement is utter bullshit, but it actually prevents Django from doing
# a lot of queries since ModelChoiceIterator stops trying to be clever once we have
# a prefetch lookup on this query...
'question',
Question.objects.none(),
to_attr='dummy'
)))
))
))
)
questions = Question.objects.filter(
event=event, container_type=Question.ContainerType.ORDER,
ask_during_checkin=False, hidden=False,
).order_by('position')
answerlist = container.answers.prefetch_related('options')
idx = 0
for questionnaire in questionnaires:
for qrow in questionnaire.rows.all():
if qrow.user_datafield:
df = qrow.user_datafield
self.fields[qrow.form_field_name] = self.build_user_question_field(request, event, answerlist, qrow, df)
else:
self.fields[qrow.form_field_name] = self.build_text_block(request, event, qrow)
idx += 1
for q in questions:
self.fields['question_%s' % q.id] = self.build_user_question_field(request, event, answerlist, q)
def clean(self):
d = super().clean()
@@ -1023,10 +1006,8 @@ class TicketLevelQuestionsForm(BaseQuestionsForm):
request = kwargs.pop('request', None)
cartpos = self.cartpos = kwargs.pop('cartpos', None)
orderpos = self.orderpos = kwargs.pop('orderpos', None)
only_user_visible = kwargs.pop('only_user_visible')
pos = cartpos or orderpos
item = pos.item
questionnaires = pos.item.relevant_questionnaires_position_purchase if only_user_visible else pos.item.relevant_questionnaires
event = kwargs.pop('event')
self.all_optional = kwargs.pop('all_optional', False)
self.attendee_addresses_required = event.settings.attendee_addresses_required and not self.all_optional
@@ -1036,15 +1017,18 @@ class TicketLevelQuestionsForm(BaseQuestionsForm):
if cartpos and item.validity_mode == Item.VALIDITY_MODE_DYNAMIC and item.validity_dynamic_start_choice:
self.fields['requested_valid_from'] = self.build_requested_valid_from_field(event, pos, item)
for questionnaire in questionnaires:
for qrow in questionnaire.rows.all():
if qrow.user_datafield:
df = qrow.user_datafield
self.fields[qrow.form_field_name] = self.build_user_question_field(request, event, pos.answerlist, qrow, df)
elif qrow.system_datafield:
self.fields[qrow.form_field_name] = self.build_system_question_field(request, event, pos, qrow)
else:
self.fields[qrow.form_field_name] = self.build_text_block(request, event, qrow)
questions = []
if item.ask_attendee_data:
questions += get_fake_attendee_questions(event.settings)
questions += pos.item.questions_to_ask
questions.sort(key=lambda q: q.position)
for q in questions:
if isinstance(q, FakeQuestion):
self.fields[q.id] = self.build_system_question_field(request, event, pos, q)
else:
self.fields['question_%s' % q.id] = self.build_user_question_field(request, event, pos.answerlist, q)
responses = question_form_fields.send(sender=event, position=pos)
data = pos.meta_info_data
@@ -1109,20 +1093,21 @@ class TicketLevelQuestionsForm(BaseQuestionsForm):
)
def build_system_question_field(self, request, event, pos, qc):
if qc.system_datafield == QuestionnaireRow.SystemDatafield.ATTENDEE_NAME_PARTS:
field_name = qc.id
if field_name == 'attendee_name_parts':
return NamePartsFormField(
max_length=255,
required=qc.required and not self.all_optional,
scheme=event.settings.name_scheme,
titles=event.settings.name_scheme_titles,
label=self.make_label(qc),
label=escape(qc.question),
help_text=rich_text(qc.help_text),
initial=pos.attendee_name_parts,
)
if qc.system_datafield == QuestionnaireRow.SystemDatafield.ATTENDEE_EMAIL:
if field_name == 'attendee_email':
return forms.EmailField(
required=qc.required and not self.all_optional,
label=self.make_label(qc),
label=escape(qc.question),
help_text=rich_text(qc.help_text),
initial=pos.attendee_email,
widget=forms.EmailInput(
@@ -1131,19 +1116,19 @@ class TicketLevelQuestionsForm(BaseQuestionsForm):
}
)
)
if qc.system_datafield == QuestionnaireRow.SystemDatafield.COMPANY:
if field_name == 'company':
return forms.CharField(
required=qc.required and not self.all_optional,
label=self.make_label(qc),
label=escape(qc.question),
help_text=rich_text(qc.help_text),
max_length=255,
initial=pos.company,
)
if qc.system_datafield == QuestionnaireRow.SystemDatafield.STREET:
if field_name == 'street':
return forms.CharField(
required=qc.required and not self.all_optional,
label=self.make_label(qc),
label=escape(qc.question),
help_text=rich_text(qc.help_text),
widget=forms.Textarea(attrs={
'rows': 2,
@@ -1152,21 +1137,21 @@ class TicketLevelQuestionsForm(BaseQuestionsForm):
}),
initial=pos.street,
)
if qc.system_datafield == QuestionnaireRow.SystemDatafield.ZIPCODE:
if field_name == 'zipcode':
return forms.CharField(
required=False,
max_length=30,
label=self.make_label(qc),
label=escape(qc.question),
help_text=rich_text(qc.help_text),
initial=pos.zipcode,
widget=forms.TextInput(attrs={
'autocomplete': 'postal-code',
}),
)
if qc.system_datafield == QuestionnaireRow.SystemDatafield.CITY:
if field_name == 'city':
return forms.CharField(
required=False,
label=self.make_label(qc),
label=escape(qc.question),
help_text=rich_text(qc.help_text),
max_length=255,
initial=pos.city,
@@ -1174,13 +1159,13 @@ class TicketLevelQuestionsForm(BaseQuestionsForm):
'autocomplete': 'address-level2',
}),
)
if qc.system_datafield == QuestionnaireRow.SystemDatafield.COUNTRY:
if field_name == 'country':
country = pos.country or guess_country_from_request(request, event)
return CountryField(
countries=CachedCountries
).formfield(
required=qc.required and not self.all_optional,
label=self.make_label(qc),
label=escape(qc.question),
help_text=rich_text(qc.help_text),
initial=country,
widget=forms.Select(attrs={
@@ -1188,7 +1173,7 @@ class TicketLevelQuestionsForm(BaseQuestionsForm):
'data-trigger-address-info': 'on',
}),
)
if qc.system_datafield == QuestionnaireRow.SystemDatafield.STATE:
if field_name == 'state':
country = pos.country or guess_country_from_request(request, event)
c = [('', '---')]
fprefix = str(self.prefix) + '-' if self.prefix is not None and self.prefix != '-' else ''
@@ -1208,7 +1193,7 @@ class TicketLevelQuestionsForm(BaseQuestionsForm):
del self.data[fprefix + 'state']
field = forms.ChoiceField(
label=self.make_label(qc),
label=escape(qc.question),
help_text=rich_text(qc.help_text),
required=False,
choices=c,
+2 -2
View File
@@ -71,8 +71,8 @@ class EmailTransmissionType(TransmissionType):
def transmission_info_to_form_data(self, transmission_info: dict) -> dict:
return {
"transmission_email_other": bool(transmission_info.get("transmission_email_address")),
"transmission_email_address": transmission_info.get("transmission_email_address"),
"transmission_email_other": bool((transmission_info or {}).get("transmission_email_address")),
"transmission_email_address": (transmission_info or {}).get("transmission_email_address"),
}
def form_data_to_transmission_info(self, form_data: dict) -> dict:
@@ -39,14 +39,8 @@ class Command(BaseCommand):
parser.add_argument(
'--print-sql',
action='store_true',
help='Print all SQL queries (needs package `django-extensions`).',
help='Print all SQL queries.',
)
parser.description = "django-scopes aware shell"
parser.epilog = """
To wrap shell in scopes_disabled (completely ignore django-scopes), add --override.
For more specific scopes, add --model__lookup=value flags, e.g. --organizer__slug=demo
"""
def handle(self, *args, **options):
try:
@@ -1,316 +0,0 @@
# Generated by Django 4.2.29 on 2026-03-19 14:24
import json
import logging
from collections import namedtuple
from itertools import chain, groupby
import django.db.models.deletion
import i18nfield.fields
from django.db import migrations, models
from django.db.models import F
from django.utils.translation import pgettext_lazy
from i18nfield.strings import LazyI18nString
import pretix.base.models.base
import pretix.base.models.fields
from pretix.base.i18n import language
from pretix.helpers.iter import sort_groupby, sort_groupby_exp
logger = logging.getLogger(__name__)
FakeQuestion = namedtuple(
'FakeQuestion', 'id question position required help_text'
)
def get_fake_questions(settings):
def b(s):
return s == 'True'
fq = []
sqo = json.loads(settings.get('system_question_order', '{}'))
_ = LazyI18nString.from_gettext
if LazyI18nString(settings.get('attendee_data_explanation_text', '')):
fq.append(FakeQuestion(None, '', -1, False, settings.get('attendee_data_explanation_text', '')))
if b(settings.get('attendee_names_asked', 'True')):
fq.append(FakeQuestion('@attendee_name_parts', _('Attendee name'), sqo.get('attendee_name_parts', 0), b(settings.get('attendee_names_required')), None))
if b(settings.get('attendee_emails_asked')):
fq.append(FakeQuestion('@attendee_email', _('Attendee email'), sqo.get('attendee_email', 0), b(settings.get('attendee_emails_required')), None))
if b(settings.get('attendee_company_asked')):
fq.append(FakeQuestion('@company', _('Company'), sqo.get('company', 0), b(settings.get('attendee_company_required')), None))
if b(settings.get('attendee_addresses_asked')):
fq.append(FakeQuestion('@street', _('Street'), sqo.get('street', 0), b(settings.get('attendee_addresses_required')), None))
fq.append(FakeQuestion('@zipcode', _('ZIP code'), sqo.get('zipcode', 0), b(settings.get('attendee_addresses_required')), None))
fq.append(FakeQuestion('@city', _('City'), sqo.get('city', 0), b(settings.get('attendee_addresses_required')), None))
fq.append(FakeQuestion('@state', _(pgettext_lazy("address", "State")), sqo.get('country', 0), b(settings.get('attendee_addresses_required')), None))
fq.append(FakeQuestion('@country', _('Country'), sqo.get('country', 0), b(settings.get('attendee_addresses_required')), None))
return fq
def migrate_questions_forward(apps, schema_editor):
from django.utils.translation import (
get_supported_language_variant, gettext as _,
)
Event = apps.get_model("pretixbase", "Event")
Item = apps.get_model("pretixbase", "Item")
Question = apps.get_model("pretixbase", "Question")
Questionnaire = apps.get_model("pretixbase", "Questionnaire")
QuestionnaireRow = apps.get_model("pretixbase", "QuestionnaireRow")
EventSettingsStore = apps.get_model('pretixbase', 'Event_SettingsStore')
qc_candidate = namedtuple('qc_candidate', ['item_info', 'question_id', 'question'])
def create_grouped_item_questionnaires(event, qc_candidates_iter, label_prefix, questionnaire_type, personalized_items):
# group by item, creating a unique questionnaire per item -> iter[tuple[list[Question], item_info]]
item_questionnaires = (
([c.question for c in group], item_info)
for item_info, group in sort_groupby(
qc_candidates_iter,
group_key=lambda c: c.item_info,
inner_sort_key=lambda c: c.question.position,
)
)
# group again, combining all questionnaires containing an identical set of questions (by means of grouping by a list of item-ids)
merged_questionnaires = sort_groupby_exp(item_questionnaires, group_key=lambda questions, item_info: [str(q.id) for q in questions])
for _unused, grouped_data in merged_questionnaires:
questions = grouped_data[0][0]
item_infos = [item_info for _c, item_info in grouped_data if item_info is not None]
internal_name = label_prefix + ', '.join(str(ii.internal_name or ii.name) for ii in item_infos)
compat_personalization = False
if all(ii.personalized for ii in item_infos) and len(item_infos) == len(personalized_items):
if questionnaire_type == "position_purchase":
# if we have a questionnaire for exactly all personalized items, we just call it "Attendee data"
# (same as the default questionnaire for new events)
internal_name = _('Attendee data')
compat_personalization = True
else:
internal_name = label_prefix + _('personalized products')
if len(internal_name) > 255:
internal_name = internal_name[:250] + ' ...'
# create questionnaires and rows
questionnaire = Questionnaire.objects.create(
event=event, type=questionnaire_type, position=0, all_sales_channels=True,
internal_name=internal_name, compat_personalization=compat_personalization
)
questionnaire.items.set([ii.id for ii in item_infos])
valid_deps = {question.id for question in questions}
new_rows = {}
deps_to_add = []
for position, question in enumerate(questions):
if isinstance(question, FakeQuestion):
QuestionnaireRow.objects.create(
questionnaire=questionnaire,
position=position + 1,
system_datafield=question.id,
required=question.required,
label=question.question,
help_text=question.help_text,
)
else:
if question.dependency_question_id and question.dependency_question_id not in valid_deps:
logger.warning('Question with invalid dependency ignored %s/%s/%d', event.organizer.slug, event.slug, question.id)
continue
new_rows[question.id] = QuestionnaireRow.objects.create(
questionnaire=questionnaire,
position=position + 1,
user_datafield=question,
required=question.required,
label=question.question,
help_text=question.help_text,
dependency_values=question.dependency_values,
)
if question.dependency_question:
deps_to_add.append((question.id, question.dependency_question.id))
for q, dep in deps_to_add:
new_rows[q].dependency_question = new_rows[dep]
new_rows[q].save()
for event in Event.objects.iterator():
# get relevant settings
settings = {
setting.key: setting.value for setting in EventSettingsStore.objects.filter(object_id=event.id, key__in=(
'system_question_order', 'attendee_names_asked', 'attendee_names_required', 'attendee_emails_asked', 'attendee_emails_required',
'attendee_company_asked', 'attendee_company_required', 'attendee_addresses_asked', 'attendee_addresses_required', 'locale',
'attendee_data_explanation_text',
))
}
with language(get_supported_language_variant(settings.get('locale', 'en'))):
# [P] get all ticket-level questions (user-defined and system provided), along with the products for which they're asked
questions = event.questions.filter(container_type='P')
personalized_items = event.items.filter(personalized=True).values_list('id', 'internal_name', 'name', 'personalized', named=True)
# [position_checkout] presale
rows = chain((
qc_candidate(item, 0, q)
for q in get_fake_questions(settings)
for item in personalized_items
), (
qc_candidate(item, q.id, q)
for q in questions.filter(hidden=False, ask_during_checkin=False)
for item in q.items.values_list('id', 'internal_name', 'name', 'personalized', named=True)
))
# Questionnaire.QuestionnaireType.POSITION_PURCHASE == "position_purchase"
create_grouped_item_questionnaires(event, rows, '', "position_purchase", personalized_items)
# [position_checkin] checkin
rows = chain((
qc_candidate(item, q.id, q)
for q in questions.filter(ask_during_checkin=True)
for item in q.items.values_list('id', 'internal_name', 'name', 'personalized', named=True)
))
# Questionnaire.QuestionnaireType.POSITION_CHECKIN == "position_checkin"
create_grouped_item_questionnaires(event, rows, _('Check-in questions for '), "position_checkin", personalized_items)
# [position_hidden] hidden
rows = chain((
qc_candidate(item, q.id, q)
for q in questions.filter(hidden=True, ask_during_checkin=False)
for item in q.items.values_list('id', 'internal_name', 'name', 'personalized', named=True)
))
# Questionnaire.QuestionnaireType.POSITION_HIDDEN == "position_hidden"
create_grouped_item_questionnaires(event, rows, _('Hidden questions for '), "position_hidden", personalized_items)
if len(personalized_items) == 0:
rows = chain((
qc_candidate(None, 0, q)
for q in get_fake_questions(settings)
))
create_grouped_item_questionnaires(event, rows, '', "position_purchase", personalized_items)
# [O] get all order-level questions
questions = list(event.questions.filter(container_type='O', hidden=False).order_by('position'))
if questions:
# create questionnaires and rows
questionnaire = Questionnaire.objects.create(
event=event, type="order_purchase", position=0, all_sales_channels=True,
internal_name=_('Per-order questions'),
)
valid_deps = {question.id for question in questions}
new_rows = {}
deps_to_add = []
for position, question in enumerate(questions):
if question.dependency_question_id and question.dependency_question_id not in valid_deps:
logger.warning('Question with invalid dependency ignored %s/%s/%d', event.organizer.slug, event.slug, question.id)
continue
new_rows[question.id] = QuestionnaireRow.objects.create(
questionnaire=questionnaire,
position=position + 1,
user_datafield=question,
required=question.required,
label=question.question,
help_text=question.help_text,
dependency_values=question.dependency_values,
)
if question.dependency_question:
deps_to_add.append((question.id, question.dependency_question.id))
for q, dep in deps_to_add:
new_rows[q].dependency_question = new_rows[dep]
new_rows[q].save()
for question in event.questions.all():
question.internal_name = str(question.question)
if question.print_on_invoice:
question.print_on_invoice_label = question.question
question.save()
def migrate_questions_backward(apps, schema_editor):
Question = apps.get_model("pretixbase", "Question")
Question.objects.filter(question__isnull=True).update(question=F('internal_name'))
def no_op(apps, schema_editor):
pass
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0311_fix_unshredded_invoices'),
]
operations = [
migrations.CreateModel(
name='Questionnaire',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False)),
('internal_name', models.CharField(max_length=255)),
('type', models.CharField(max_length=25)),
('position', models.PositiveIntegerField(default=0)),
('all_sales_channels', models.BooleanField(default=True)),
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='questionnaires', to='pretixbase.event')),
('items', models.ManyToManyField(related_name='questionnaires', to='pretixbase.item')),
('limit_sales_channels', models.ManyToManyField(to='pretixbase.saleschannel')),
('compat_personalization', models.BooleanField(default=False)),
],
options={
'abstract': False,
},
bases=(models.Model, pretix.base.models.base.LoggingMixin),
),
migrations.CreateModel(
name='QuestionnaireRow',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False)),
('position', models.PositiveIntegerField(default=0)),
('system_datafield', models.CharField(max_length=25, null=True)),
('required', models.BooleanField(default=False)),
('label', i18nfield.fields.I18nTextField()),
('help_text', i18nfield.fields.I18nTextField(null=True)),
('dependency_values', pretix.base.models.fields.MultiStringField(default=[])),
('dependency_question', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='dependent_questions', to='pretixbase.questionnairerow')),
('questionnaire', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='rows', to='pretixbase.questionnaire')),
('user_datafield', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='referenced_by', to='pretixbase.question')),
],
options={
'abstract': False,
},
bases=(models.Model, pretix.base.models.base.LoggingMixin),
),
migrations.AddField(
model_name='question',
name='internal_name',
field=models.CharField(default='', max_length=255),
preserve_default=False,
),
migrations.AddField(
model_name='question',
name='print_on_invoice_label',
field=i18nfield.fields.I18nTextField(null=True),
),
migrations.RunPython(
migrate_questions_forward,
no_op,
),
migrations.AlterField(
model_name='question',
name='question',
field=i18nfield.fields.I18nTextField(null=True, db_column='question'),
),
migrations.RunPython(
no_op,
migrate_questions_backward,
),
migrations.RenameField(
model_name='question',
old_name='question',
new_name='tbd_question',
),
# add tbd_hidden, tbd_ask_during_checkin, ...
# TODO(questionnaires) remove old columns from Question model
]
+10 -34
View File
@@ -665,7 +665,7 @@ class CheckinTextColumn(ImportColumn):
order.checkin_text = value
class BaseQuestionColumn(ImportColumn):
class QuestionColumn(ImportColumn):
def __init__(self, event, q):
self.q = q
self.option_resolve_cache = defaultdict(set)
@@ -688,7 +688,7 @@ class BaseQuestionColumn(ImportColumn):
@property
def verbose_name(self):
return _('Question') + ': ' + str(self.q.internal_name)
return _('Question') + ': ' + str(self.q.question)
@property
def identifier(self):
@@ -714,16 +714,6 @@ class BaseQuestionColumn(ImportColumn):
else:
return self.q.clean_answer(value)
def save(self, order):
for a in getattr(order, '_answers', []):
a.order = a.order # This is apparently required after save() again
a.orderposition = a.orderposition # This is apparently required after save() again
a.save()
if hasattr(a, '_options'):
a.options.add(*a._options)
class PositionQuestionColumn(BaseQuestionColumn):
def assign(self, value, order, position, invoice_address, **kwargs):
if value is not None:
if not hasattr(order, '_answers'):
@@ -739,24 +729,12 @@ class PositionQuestionColumn(BaseQuestionColumn):
else:
order._answers.append(QuestionAnswer(question=self.q, answer=str(value), orderposition=position))
class OrderQuestionColumn(BaseQuestionColumn):
order_level = True
def assign(self, value, order, position, invoice_address, **kwargs):
if value is not None:
if not hasattr(order, '_answers'):
order._answers = []
if isinstance(value, QuestionOption):
a = QuestionAnswer(order=order, question=self.q, answer=str(value))
a._options = [value]
order._answers.append(a)
elif isinstance(value, list):
a = QuestionAnswer(order=order, question=self.q, answer=', '.join(str(v) for v in value))
a._options = value
order._answers.append(a)
else:
order._answers.append(QuestionAnswer(question=self.q, answer=str(value), order=order))
def save(self, order):
for a in getattr(order, '_answers', []):
a.orderposition = a.orderposition # This is apparently required after save() again
a.save()
if hasattr(a, '_options'):
a.options.add(*a._options)
class CustomerColumn(ImportColumn):
@@ -810,8 +788,6 @@ def get_order_import_columns(event):
InvoiceAddressVATID(event),
InvoiceAddressReference(event),
]
for q in event.orderdatafields.prefetch_related('options').exclude(type=Question.TYPE_FILE):
default.append(OrderQuestionColumn(event, q))
for n, l, w in scheme['fields']:
default.append(AttendeeNamePart(event, n, l))
default += [
@@ -834,8 +810,8 @@ def get_order_import_columns(event):
Expires(event),
Comment(event),
]
for q in event.positiondatafields.prefetch_related('options').exclude(type=Question.TYPE_FILE):
default.append(PositionQuestionColumn(event, q))
for q in event.questions.prefetch_related('options').exclude(type=Question.TYPE_FILE):
default.append(QuestionColumn(event, q))
for recv, resp in order_import_columns.send(sender=event):
default += resp
+2 -2
View File
@@ -37,8 +37,8 @@ from .invoices import Invoice, InvoiceLine, invoice_filename
from .items import (
Item, ItemAddOn, ItemBundle, ItemCategory, ItemMetaProperty, ItemMetaValue,
ItemProgramTime, ItemVariation, ItemVariationMetaValue, Question,
Questionnaire, QuestionnaireRow, QuestionOption, Quota, SubEventItem,
SubEventItemVariation, itempicture_upload_to,
QuestionOption, Quota, SubEventItem, SubEventItemVariation,
itempicture_upload_to,
)
from .log import LogEntry
from .mail import OutgoingMail
+21 -44
View File
@@ -79,7 +79,6 @@ from pretix.helpers.thumb import get_thumbnail
from ..settings import settings_hierarkey
from .organizer import Organizer, Team
from ...helpers.models import copy_objects, filter_with_cache
if TYPE_CHECKING:
from hierarkey.proxy import HierarkeyProxy
@@ -738,20 +737,6 @@ class Event(EventMixin, LoggedModel):
self.settings.mail_send_order_approved_attendee = True
self.settings.mail_send_order_approved_free_attendee = True
self.settings.mail_send_download_reminder_attendee = True
self.get_default_questionnaire()
def get_default_questionnaire(self):
from . import Questionnaire, QuestionnaireRow
questionnaire, created = self.questionnaires.get_or_create(compat_personalization=True, defaults={
'position': 0, 'internal_name': str(_('Attendee data')),
'type': Questionnaire.QuestionnaireType.POSITION_PURCHASE,
})
if created:
questionnaire.rows.create(
position=0, label=str(_('Attendee name')),
system_datafield=QuestionnaireRow.SystemDatafield.ATTENDEE_NAME_PARTS)
return questionnaire
@property
def social_image(self):
@@ -911,7 +896,7 @@ class Event(EventMixin, LoggedModel):
from ..signals import event_copy_data
from . import (
Discount, Item, ItemAddOn, ItemBundle, ItemCategory, ItemMetaValue,
ItemProgramTime, ItemVariationMetaValue, Question, Questionnaire, Quota,
ItemProgramTime, ItemVariationMetaValue, Question, Quota,
)
is_cross_organizer = other.organizer_id != self.organizer_id
@@ -940,8 +925,6 @@ class Event(EventMixin, LoggedModel):
)
)
sales_channel_map = defaultdict(lambda: None, {s.identifier: s for s in self.organizer.sales_channels.all()})
if not skip_meta_data:
for emv in EventMetaValue.objects.filter(event=other):
emv.pk = None
@@ -1113,19 +1096,27 @@ class Event(EventMixin, LoggedModel):
if not d.all_sales_channels:
d.limit_sales_channels.set(self.organizer.sales_channels.filter(identifier__in=[s.identifier for s in limit_sales_channels]))
question_map = copy_objects(
Question.objects.filter(event=other).prefetch_related('options'),
to=('event', self), child_relations=[('options', dict())]
)
question_map = {}
for q in Question.objects.filter(event=other).prefetch_related('items', 'options'):
items = list(q.items.all())
opts = list(q.options.all())
question_map[q.pk] = q
q.pk = None
q._prefetched_objects_cache = {}
q.event = self
q.save(force_insert=True)
q.log_action('pretix.object.cloned')
qrow_map = dict()
copy_objects(
Questionnaire.objects.filter(event=other).prefetch_related('items', 'limit_sales_channels'),
to=('event', self), translate=[('items', 'id', item_map), ('limit_sales_channels', 'identifier', sales_channel_map)],
child_relations=[
('rows', dict(obj_map=qrow_map, translate=[('user_datafield', 'id', question_map), ('dependency_question', 'id', qrow_map)]))
],
)
for i in items:
q.items.add(item_map[i.pk])
for o in opts:
o.pk = None
o.question = q
o.save(force_insert=True)
for q in self.questions.filter(dependency_question__isnull=False):
q.dependency_question = question_map[q.dependency_question_id]
q.save(update_fields=['dependency_question'])
def _walk_rules(rules):
if isinstance(rules, dict):
@@ -1435,10 +1426,6 @@ class Event(EventMixin, LoggedModel):
return issues
@property
def sales_channels(self):
return self.organizer.sales_channels if self.all_sales_channels else self.limit_sales_channels
def get_users_with_any_permission(self):
"""
Returns a queryset of users who have any permission to this event.
@@ -1560,16 +1547,6 @@ class Event(EventMixin, LoggedModel):
if presale_start > presale_end:
raise ValidationError(_('The event\'s presale cannot end before it starts.'))
@property
def orderdatafields(self):
from . import Question
return filter_with_cache(self.questions, container_type=Question.ContainerType.ORDER)
@property
def positiondatafields(self):
from . import Question
return filter_with_cache(self.questions, container_type=Question.ContainerType.ORDERPOSITION)
class SubEvent(EventMixin, LoggedModel):
"""
+61 -334
View File
@@ -41,7 +41,6 @@ import warnings
from collections import Counter, OrderedDict
from datetime import date, datetime, time, timedelta
from decimal import Decimal, DecimalException
from itertools import groupby
from typing import Optional, Tuple
from zoneinfo import ZoneInfo
@@ -379,6 +378,8 @@ class Item(LoggedModel):
:type tax_rate: decimal.Decimal
:param admission: ``True``, if this item allows persons to enter the event (as opposed to e.g. merchandise)
:type admission: bool
:param personalized: ``True``, if attendee information should be collected for this ticket
:type personalized: bool
:param picture: A product picture to be shown next to the product description
:type picture: File
:param available_from: The date this product goes on sale
@@ -531,13 +532,12 @@ class Item(LoggedModel):
),
default=False
)
tbd_personalized = models.BooleanField( # TODO(questionnaires): field to be deleted
personalized = models.BooleanField(
verbose_name=_("Is a personalized ticket"),
help_text=_(
'Whether or not buying this product allows to enter attendee information'
),
default=False,
db_column='personalized',
default=False
)
generate_tickets = models.BooleanField(
verbose_name=_("Generate tickets"),
@@ -822,33 +822,9 @@ class Item(LoggedModel):
return self.event.settings.show_quota_left
return self.show_quota_left
def get_relevant_questionnaires(self, questionnaire_type, sales_channel):
"""
Questionnaires attached to this item, optionally filtered by type and sales channel.
If the model was fetched via a QuerySet on which prefetch_relevant_questionnaires was used,
the cached list is returned. In that case, the sales_channel parameter is ignored.
"""
cache_key = 'relevant_questionnaires' + (f'_{questionnaire_type}' if questionnaire_type else '')
if (questionnaires := getattr(self, cache_key, None)) is not None:
return questionnaires
else:
qs = self.questionnaires.all()
if questionnaire_type is not None:
qs = qs.filter(questionnaire__type=questionnaire_type)
if sales_channel is not None:
qs = qs.filter(Q(questionnaire__all_sales_channels=True) | Q(questionnaire__limit_sales_channels=sales_channel))
return qs
def get_asked_questions(self, questionnaire_type=None, sales_channel=None):
qs = QuestionnaireRow.objects.filter(
Q(system_datafield__isnull=False) | Q(user_datafield_id__isnull=False),
questionnaire__items=self,
) # .prefetch_related('user_datafield')
if questionnaire_type is not None:
qs = qs.filter(questionnaire__type=questionnaire_type)
if sales_channel is not None:
qs = qs.filter(Q(questionnaire__all_sales_channels=True) | Q(questionnaire__limit_sales_channels=sales_channel))
return qs
@property
def ask_attendee_data(self):
return self.admission and self.personalized
def tax(self, price=None, base_price_is='auto', currency=None, invoice_address=None, override_tax_rate=None,
include_bundled=False, force_fixed_gross_price=False):
@@ -1589,14 +1565,12 @@ class ItemBundle(models.Model):
raise ValidationError(_('The count needs to be equal to or greater than zero.'))
class Question(LoggedModel): # TODO(questionnaires) - rename to Datafield ?
class Question(LoggedModel):
"""
A question is a data field that can be used to extend an order or a ticket by custom
information, e.g. "Attendee age". To be actually useful, questions need to be added to
one or multiple Questionnaires. The answers may be found in QuestionAnswers, attached
to Orders, OrderPositions or CartPositions.
A question can allow one of several input types, currently:
A question is an input field that can be used to extend a ticket by custom information,
e.g. "Attendee age". The answers are found next to the position. The answers may be found
in QuestionAnswers, attached to OrderPositions/CartPositions. A question can allow one of
several input types, currently:
* a number (``TYPE_NUMBER``)
* a one-line string (``TYPE_STRING``)
@@ -1616,7 +1590,7 @@ class Question(LoggedModel): # TODO(questionnaires) - rename to Datafield ?
:param required: Whether answering this question is required for submitting an order including
items associated with this question.
:type required: bool
:param items: TO BE REMOVED
:param items: A set of ``Items`` objects that this question should be applied to
:param ask_during_checkin: Whether to ask this question during check-in instead of during check-out.
:type ask_during_checkin: bool
:param show_during_checkin: Whether to show the answer to this question during check-in.
@@ -1633,22 +1607,6 @@ class Question(LoggedModel): # TODO(questionnaires) - rename to Datafield ?
class ContainerType(models.TextChoices):
ORDER = "O", _("Order")
ORDERPOSITION = "P", _("Order position")
class FieldType(models.TextChoices):
NUMBER = "N", _("Number")
STRING = "S", _("Text (one line)")
TEXT = "T", _("Multiline text")
BOOLEAN = "B", _("Yes/No")
CHOICE = "C", _("Choose one from a list")
CHOICE_MULTIPLE = "M", _("Choose multiple from a list")
FILE = "F", _("File upload")
DATE = "D", _("Date")
TIME = "H", _("Time")
DATETIME = "W", _("Date and time")
COUNTRYCODE = "CC", _("Country code (ISO 3166-1 alpha-2)")
PHONENUMBER = "TEL", _("Phone number")
# compat
TYPE_NUMBER = "N"
TYPE_STRING = "S"
TYPE_TEXT = "T"
@@ -1661,12 +1619,23 @@ class Question(LoggedModel): # TODO(questionnaires) - rename to Datafield ?
TYPE_DATETIME = "W"
TYPE_COUNTRYCODE = "CC"
TYPE_PHONENUMBER = "TEL"
TYPE_CHOICES = FieldType.choices
TYPE_CHOICES = (
(TYPE_NUMBER, _("Number")),
(TYPE_STRING, _("Text (one line)")),
(TYPE_TEXT, _("Multiline text")),
(TYPE_BOOLEAN, _("Yes/No")),
(TYPE_CHOICE, _("Choose one from a list")),
(TYPE_CHOICE_MULTIPLE, _("Choose multiple from a list")),
(TYPE_FILE, _("File upload")),
(TYPE_DATE, _("Date")),
(TYPE_TIME, _("Time")),
(TYPE_DATETIME, _("Date and time")),
(TYPE_COUNTRYCODE, _("Country code (ISO 3166-1 alpha-2)")),
(TYPE_PHONENUMBER, _("Phone number")),
)
UNLOCALIZED_TYPES = [TYPE_DATE, TYPE_TIME, TYPE_DATETIME]
ASK_DURING_CHECKIN_UNSUPPORTED = []
SHOW_DURING_CHECKIN_UNSUPPORTED = [TYPE_FILE]
TYPES_ALLOWED_AS_DEPENDENCIES = {TYPE_BOOLEAN, TYPE_CHOICE, TYPE_CHOICE_MULTIPLE}
event = models.ForeignKey(
Event,
@@ -1679,13 +1648,8 @@ class Question(LoggedModel): # TODO(questionnaires) - rename to Datafield ?
verbose_name=_("Asked on"),
default=ContainerType.ORDERPOSITION,
)
internal_name = models.CharField(
verbose_name=_("Internal name"),
max_length=255,
)
tbd_question = I18nTextField( # TODO(questionnaires) : to be removed
verbose_name=_("Internal name"),
null=True, blank=True, db_column="question",
question = I18nTextField(
verbose_name=_("Question")
)
identifier = models.CharField(
max_length=190,
@@ -1699,63 +1663,54 @@ class Question(LoggedModel): # TODO(questionnaires) - rename to Datafield ?
),
],
)
#help_text = I18nTextField(
# # TODO(questionnaires) : to be removed
# verbose_name=_("Help text"),
# help_text=_("If the question needs to be explained or clarified, do it here!"),
# null=True, blank=True,
#)
help_text = I18nTextField(
verbose_name=_("Help text"),
help_text=_("If the question needs to be explained or clarified, do it here!"),
null=True, blank=True,
)
type = models.CharField(
max_length=5,
choices=FieldType.choices,
choices=TYPE_CHOICES,
verbose_name=_("Question type")
)
tbd_required = models.BooleanField( # TODO(questionnaires) : to be removed, -> QuestionnaireRow
required = models.BooleanField(
default=False,
verbose_name=_("Required question"),
db_column="required",
verbose_name=_("Required question")
)
# items = models.ManyToManyField( # TODO(questionnaires) : to be removed, -> Questionnaire
# Item,
# related_name='questions',
# verbose_name=_("Products"),
# blank=True,
# help_text=_('This question will be asked to buyers of the selected products')
# )
tbd_position = models.PositiveIntegerField( # TODO(questionnaires) : to be removed, -> Questionnaire + QuestionnaireRow
items = models.ManyToManyField(
Item,
related_name='questions',
verbose_name=_("Products"),
blank=True,
help_text=_('This question will be asked to buyers of the selected products')
)
position = models.PositiveIntegerField(
default=0,
verbose_name=_("Position"),
db_column="position",
verbose_name=_("Position")
)
tbd_ask_during_checkin = models.BooleanField( # TODO(questionnaires) : to be removed
ask_during_checkin = models.BooleanField(
verbose_name=_('Ask during check-in instead of in the ticket buying process'),
help_text=_('Not supported by all check-in apps for all question types.'),
default=False,
db_column="ask_during_checkin",
default=False
)
show_during_checkin = models.BooleanField(
verbose_name=_('Show answer during check-in'),
help_text=_('Not supported by all check-in apps for all question types.'),
default=False
)
tbd_hidden = models.BooleanField( # to be removed
hidden = models.BooleanField(
verbose_name=_('Hidden question'),
help_text=_('This question will only show up in the backend.'),
default=False,
db_column="hidden",
default=False
)
print_on_invoice = models.BooleanField(
verbose_name=_('Print answer on invoices'),
default=False
)
print_on_invoice_label = I18nTextField(
verbose_name=_('Label on invoice'),
null=True, blank=True,
)
dependency_question = models.ForeignKey( # TODO(questionnaires) : to be removed, -> QuestionnaireRow
dependency_question = models.ForeignKey(
'Question', null=True, blank=True, on_delete=models.SET_NULL, related_name='dependent_questions'
)
dependency_values = MultiStringField(default=[]) # TODO(questionnaires) : to be removed, -> QuestionnaireRow
dependency_values = MultiStringField(default=[])
valid_number_min = models.DecimalField(decimal_places=6, max_digits=30, null=True, blank=True,
verbose_name=_('Minimum value'),
help_text=_('Currently not supported in our apps and during check-in'))
@@ -1794,13 +1749,13 @@ class Question(LoggedModel): # TODO(questionnaires) - rename to Datafield ?
objects = ScopedManager(organizer='event__organizer')
class Meta:
verbose_name = _("Data field")
verbose_name_plural = _("Data fields")
ordering = ('internal_name', 'id')
verbose_name = _("Question")
verbose_name_plural = _("Questions")
ordering = ('position', 'id')
unique_together = (('event', 'identifier'),)
def __str__(self):
return str(self.internal_name)
return str(self.question)
def delete(self, *args, **kwargs):
super().delete(*args, **kwargs)
@@ -1834,12 +1789,15 @@ class Question(LoggedModel): # TODO(questionnaires) - rename to Datafield ?
@property
def sortkey(self):
return self.id
return self.position, self.id
def __lt__(self, other) -> bool:
return self.sortkey < other.sortkey
def clean_answer(self, answer):
if self.required:
if not answer or (self.type == Question.TYPE_BOOLEAN and answer not in ("true", "True", True)):
raise ValidationError(_('An answer to this question is required to proceed.'))
if not answer:
if self.type == Question.TYPE_BOOLEAN:
return False
@@ -1944,7 +1902,7 @@ class Question(LoggedModel): # TODO(questionnaires) - rename to Datafield ?
return answer
@staticmethod
def clean_items(event, items): # TODO(questionnaires) : remove method / move to qc
def clean_items(event, items):
for item in items:
if event != item.event:
raise ValidationError(_('One or more items do not belong to this event.'))
@@ -2025,237 +1983,6 @@ class QuestionOption(models.Model):
ordering = ('position', 'id')
class Questionnaire(LoggedModel):
class QuestionnaireType(models.TextChoices):
ORDER_PURCHASE = "order_purchase", _("Order-wide, before purchase")
POSITION_PURCHASE = "position_purchase", _("Per product, before purchase")
POSITION_ATTENDEE_ONLY = "position_attendee", _("Per product, via attendee link")
POSITION_CHECKIN = "position_checkin", _("Per product, at check-in")
POSITION_HIDDEN = "position_hidden", _("Per product, hidden")
event = models.ForeignKey(
Event,
related_name="questionnaires",
on_delete=models.CASCADE
)
internal_name = models.CharField(
verbose_name=_("Internal name"),
max_length=255,
)
type = models.CharField(
max_length=25,
choices=QuestionnaireType.choices,
verbose_name=_("Questionnaire type")
)
items = models.ManyToManyField(
Item,
related_name='questionnaires',
verbose_name=_("Products"),
blank=True,
help_text=_('This questionnaire will be asked to buyers of the selected products')
)
position = models.PositiveIntegerField(
default=0,
verbose_name=_("Position")
)
all_sales_channels = models.BooleanField(
verbose_name=_("Sell on all sales channels the product is sold on"),
default=True,
)
limit_sales_channels = models.ManyToManyField(
"SalesChannel",
verbose_name=_("Restrict to specific sales channels"),
help_text=_('The sales channel selection for the product as a whole takes precedence, so if a sales channel is '
'selected here but not on product level, the variation will not be available.'),
blank=True,
)
compat_personalization = models.BooleanField(default=False)
class Meta:
ordering = ('position', 'id')
def __str__(self) -> str:
return self.internal_name
@property
def sortkey(self):
return self.position, self.id
def __lt__(self, other) -> bool:
return self.sortkey < other.sortkey
@property
def ask_before_sale(self):
return self.type == Questionnaire.QuestionnaireType.POSITION_PURCHASE
@property
def ask_during_checkin(self):
return self.type == Questionnaire.QuestionnaireType.POSITION_CHECKIN
@property
def hidden(self):
return self.type == Questionnaire.QuestionnaireType.POSITION_HIDDEN
@staticmethod
def check_constraints(event):
errors = set()
all_questionnaires = Questionnaire.objects.filter(event=event).prefetch_related('rows', 'items')
all_sales_channels = event.sales_channels.all()
for (sales_channel, type, item_id, sdf, udf), fields in groupby(sorted(
(sales_channel, q.type, item.id, c.system_datafield or '', c.user_datafield_id or 0, q, item)
for q in all_questionnaires
for sales_channel in (q.limit_sales_channels if not q.all_sales_channels else all_sales_channels).values_list('pk', flat=True)
for item in q.items.all()
for c in q.rows.all()
), key=lambda d: (d[0], d[1], d[2], d[3], d[4])):
fields = list(fields)
if len(fields) > 1:
sales_channel, type, item_id, sdf, udf, q, item = fields[0]
questionnaires = set(q for sc, type, item, sdf, udf, q, item in fields)
df_label = _('System data field') + f' "{sdf}"' if sdf else _('User-defined data field') + f' "{str(udf)}"'
if len(questionnaires) == 1:
errors.add(_('{datafield} added twice to questionnaire "{questionnaire}"').format(
datafield=df_label, questionnaire=next(str(q) for q in questionnaires)
))
else:
errors.add(_('{datafield} added twice to the same item "{item}" via questionnaires "{questionnaires}"').format(
datafield=df_label, item=str(item), questionnaires='" and "'.join(str(q) for q in questionnaires)
))
if errors:
raise ValidationError(list(errors))
class QuestionnaireRow(LoggedModel):
class SystemDatafield(models.TextChoices):
ATTENDEE_NAME_PARTS = '@attendee_name_parts', _('Attendee name')
ATTENDEE_EMAIL = '@attendee_email', _('Attendee email')
COMPANY = '@company', _('Company')
STREET = '@street', _('Street')
ZIPCODE = '@zipcode', _('ZIP code')
CITY = '@city', _('City')
STATE = '@state', pgettext_lazy('address', 'State')
COUNTRY = '@country', _('Country')
# _name_schemes_all_fields = sorted(list(set(k for scheme in PERSON_NAME_SCHEMES.values() for k, v, w, *__ in scheme['fields'])))
_name_schemes_all_fields = ['calling_name', 'degree', 'family_name', 'full_name', 'given_name',
'latin_transcription', 'middle_name', 'salutation', 'title']
SYSTEM_DATAFIELD_NUMBERS = [
# The index in this list is used to create fake IDs for legacy APIs, so do not reorder anything!
SystemDatafield.ATTENDEE_NAME_PARTS.value,
SystemDatafield.ATTENDEE_EMAIL.value,
SystemDatafield.COMPANY.value,
SystemDatafield.STREET.value,
SystemDatafield.ZIPCODE.value,
SystemDatafield.CITY.value,
SystemDatafield.STATE.value,
SystemDatafield.COUNTRY.value,
] + [
'@attendee_name_parts:' + field
for field in _name_schemes_all_fields
]
SYSTEM_DATAFIELD_TYPES = {
SystemDatafield.ATTENDEE_NAME_PARTS.value: Question.TYPE_STRING,
SystemDatafield.ATTENDEE_EMAIL.value: Question.TYPE_STRING,
SystemDatafield.COMPANY.value: Question.TYPE_STRING,
SystemDatafield.STREET.value: Question.TYPE_STRING,
SystemDatafield.ZIPCODE.value: Question.TYPE_STRING,
SystemDatafield.CITY.value: Question.TYPE_STRING,
SystemDatafield.STATE.value: Question.TYPE_STRING,
SystemDatafield.COUNTRY.value: Question.TYPE_COUNTRYCODE,
}
questionnaire = models.ForeignKey(
Questionnaire,
related_name="rows",
on_delete=models.CASCADE
)
position = models.PositiveIntegerField(
default=0,
verbose_name=_("Position")
)
user_datafield = models.ForeignKey(
Question,
related_name="referenced_by",
on_delete=models.CASCADE,
null=True, blank=True,
)
system_datafield = models.CharField(
max_length=25,
choices=SystemDatafield.choices,
null=True, blank=True,
)
required = models.BooleanField(
default=False,
verbose_name=_("Required question")
)
label = I18nTextField(
verbose_name=_("Question")
)
help_text = I18nTextField(
verbose_name=_("Help text"),
help_text=_("If the question needs to be explained or clarified, do it here!"),
null=True, blank=True,
)
dependency_question = models.ForeignKey(
'QuestionnaireRow', null=True, blank=True, on_delete=models.SET_NULL, related_name='dependent_questions'
)
dependency_values = MultiStringField(default=[])
class Meta:
ordering = ('position', 'id')
@property
def datafield_type(self):
if self.system_datafield:
return QuestionnaireRow.SYSTEM_DATAFIELD_TYPES[self.system_datafield]
elif self.user_datafield:
return self.user_datafield.type
@property
def form_field_name(self):
if self.user_datafield_id:
return 'question_%s' % self.user_datafield_id
elif self.system_datafield:
return self.system_datafield[1:]
else:
return 'text_%s' % self.position
@property
def cooked_id(self):
if self.user_datafield_id or self.system_datafield:
return QuestionnaireRow.cook_id_from_parts(self.questionnaire_id, self.user_datafield_id, self.system_datafield)
else:
return None
@staticmethod
def cook_id_from_parts(qid, dfid, sys_df):
df_id = dfid + 100 if dfid else QuestionnaireRow.SYSTEM_DATAFIELD_NUMBERS.index(sys_df)
assert qid < 1000000000
return qid * 1000000000 + df_id
@staticmethod
def uncook_id(id):
id = int(id)
if id > 1000000000:
qid, dfid = divmod(id, 1000000000)
if dfid >= 100:
return qid, dfid - 100, None
else:
return qid, None, QuestionnaireRow.SYSTEM_DATAFIELD_NUMBERS[dfid]
else:
return None, id, None
def clean_answer(self, answer):
if not self.user_datafield:
raise ValueError('QuestionnaireRow.clean_answer is only implemented for rows referencing a user datafield')
if self.required:
if not answer or (self.user_datafield.type == Question.TYPE_BOOLEAN and answer not in ("true", "True", True)):
raise ValidationError(_('An answer to this question is required to proceed.'))
return self.user_datafield.clean_answer(answer)
class Quota(LoggedModel):
"""
A quota is a "pool of tickets". It is there to limit the number of items
+59 -227
View File
@@ -39,10 +39,9 @@ import hmac
import json
import logging
import operator
import os
import string
import warnings
from collections import Counter, namedtuple
from collections import Counter
from datetime import datetime, time, timedelta
from decimal import Decimal
from functools import reduce
@@ -54,7 +53,6 @@ import dateutil
import pycountry
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.files import File
from django.db import models, transaction
from django.db.models import (
Case, Exists, F, Max, OuterRef, Q, Subquery, Sum, Value, When,
@@ -81,7 +79,7 @@ from pretix.base.banlist import banned
from pretix.base.decimal import round_decimal
from pretix.base.email import get_email_context
from pretix.base.i18n import language
from pretix.base.models import Customer, Questionnaire, User
from pretix.base.models import Customer, User
from pretix.base.reldate import RelativeDateWrapper
from pretix.base.settings import PERSON_NAME_SCHEMES, ROUNDING_MODES
from pretix.base.signals import allow_ticket_download, order_gracefully_delete
@@ -97,9 +95,7 @@ from ._transactions import (
)
from .base import LockModel, LoggedModel
from .event import Event, SubEvent
from .items import (
Item, ItemVariation, Question, QuestionnaireRow, QuestionOption, Quota,
)
from .items import Item, ItemVariation, Question, QuestionOption, Quota
logger = logging.getLogger(__name__)
@@ -112,175 +108,6 @@ def generate_position_secret():
raise TypeError("Function no longer exists, use secret generators")
FakeQuestionnaireRow = namedtuple('FakeQuestionnaireRow', ('user_datafield', 'label', 'answer'))
class SystemDatafieldAnswer:
def __init__(self, answer):
self.answer = answer
def to_dependency_values(self):
return [self.answer]
class QuestionnaireRenderer:
def __init__(self, qrows, system_answers, answerlist):
self.qrows = qrows
self.row_cache = {
q.pk: q for q in self.qrows
}
self.system_answers = system_answers
self.answerlist = answerlist
def _row_is_visible(self, parentid, qvals):
# TODO(questionnaires): country-dependent address logic
if parentid is None:
return True
if parentid not in self.row_cache:
return False
parentrow = self.row_cache[parentid]
if not self._row_is_visible(parentrow.dependency_question_id, parentrow.dependency_values):
return False
answer_values = self.get_dependency_answer_values(parentrow)
return answer_values and any(qval in answer_values for qval in qvals)
def row_is_required(self, qrow):
# TODO(questionnaires): country-dependent address logic
return qrow.required and self._row_is_visible(qrow.dependency_question_id, qrow.dependency_values)
@cached_property
def answer_cache(self):
return {
**self.system_answers,
**{aw.question_id: aw for aw in self.answerlist},
}
def get_system_answer(self, field_name):
try:
return self.system_answers[field_name]
except KeyError:
raise KeyError('Unknown system datafield name: ' + field_name)
def get_dependency_answer_values(self, qc):
if answer := self.get_answer_object(qc):
return answer.to_dependency_values()
def get_answer_object(self, qc):
if qc.user_datafield_id:
return self.answer_cache.get(qc.user_datafield_id)
elif qc.system_datafield:
return SystemDatafieldAnswer(self.get_system_answer(qc.system_datafield))
else:
raise ValueError('Questionnaire child without datafield has no answer')
@cached_property
def question_data(self) -> List[QuestionnaireRow]:
"""
Returns a list of QuestionnaireRows extended with `answer` attributes, which contains either a QuestionAnswer
object or a string (in case of system data fields).
"""
question_data = []
for qrow in self.qrows:
if not (qrow.user_datafield_id or qrow.system_datafield):
continue
try:
qrow.answer = self.answer_cache[qrow.user_datafield_id or qrow.system_datafield]
# TODO(questionnaires) - replace with `qrow.answer = self.get_answer_object(qrow)` ?
except KeyError:
pass
if self._row_is_visible(qrow.dependency_question_id, qrow.dependency_values):
question_data.append(qrow)
return question_data
def __iter__(self):
return iter(self.question_data)
def __bool__(self):
return len(self.question_data) > 0
@cached_property
def asked_questions(self):
return {qrow.user_datafield_id or qrow.system_datafield for qrow in self.question_data}
@property
def leftovers(self) -> List[FakeQuestionnaireRow]:
"""
Returns a list of questionnaire-row-like objects for all answers that exist, but are not asked in the
questionnaire. These might either exist due to questionnaire changes after orders were already created,
or due to programmatically adding answers via the API.
"""
return [FakeQuestionnaireRow(answer.question, answer.question.internal_name, answer) for answer in self.answerlist if answer.question.id not in self.asked_questions]
@property
def full_address_asked(self):
Field = QuestionnaireRow.SystemDatafield
return {Field.STREET, Field.ZIPCODE, Field.CITY, Field.STATE, Field.COUNTRY}.issubset(self.asked_questions)
class AnswerableMixin:
def set_answers(self, answers_data, ignore_duplicates=False, close_files=False, delete_missing=True, answercache=None):
questions_seen = set()
if answercache is None:
answercache = {
a_obj.question_id: a_obj for a_obj in self.answers.all()
}
for data in answers_data:
data = dict(data)
question_id = data['question'].pk
if not data.get('answer'):
if (not delete_missing) and question_id in answercache:
answercache[question_id].delete()
questions_seen.add(question_id)
continue
if question_id in questions_seen:
if ignore_duplicates:
continue
else:
raise ValidationError(f'Question {data["question"]} was sent twice.')
new_value = data['answer']
options = data.pop('options', [])
if question_id in answercache:
a_obj = answercache[question_id]
if isinstance(new_value, File):
a_obj.set_file(new_value)
if close_files: new_value.close()
elif a_obj.answer.startswith('file://') and new_value == "file:keep":
pass # keep current file
else:
for attr, value in data.items():
setattr(a_obj, attr, value)
a_obj.save()
else:
if isinstance(new_value, File):
data.pop('answer')
a_obj = self.answers.create(**data, answer='')
a_obj.set_file(new_value)
a_obj.save()
if close_files: new_value.close()
else:
a_obj = self.answers.create(**data)
a_obj.options.set(options)
questions_seen.add(a_obj.question_id)
if delete_missing:
for qid, a_obj in answercache.items():
if qid not in questions_seen:
a_obj.delete()
class OrderLevelAnswerableMixin(AnswerableMixin):
@cached_property
def rendered_questions(self):
qrows = QuestionnaireRow.objects.filter(
Q(system_datafield__isnull=False) | Q(user_datafield_id__isnull=False),
Q(questionnaire__all_sales_channels=True) | Q(questionnaire__limit_sales_channels=self.sales_channel),
questionnaire__event=self.event,
questionnaire__type=Questionnaire.QuestionnaireType.ORDER_PURCHASE,
)
return QuestionnaireRenderer(qrows=qrows, system_answers={}, answerlist=self.answers.all())
class OrderQuerySet(models.QuerySet):
def get_with_secret_check(self, code, received_secret, tag, secret_length=64):
dummy = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"[:secret_length]
@@ -309,7 +136,7 @@ class OrderQuerySet(models.QuerySet):
return order
class Order(OrderLevelAnswerableMixin, LockModel, 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
@@ -1091,7 +918,7 @@ class Order(OrderLevelAnswerableMixin, LockModel, LoggedModel):
positions = list(
self.positions.all().annotate(
has_checkin=Exists(Checkin.objects.filter(position_id=OuterRef('pk'), list__consider_tickets_used=True))
).select_related('item').prefetch_related('item__questionnaires')
).select_related('item').prefetch_related('item__questions')
)
if not self.event.settings.allow_modifications_after_checkin:
for cp in positions:
@@ -1100,8 +927,9 @@ class Order(OrderLevelAnswerableMixin, LockModel, LoggedModel):
if self.event.settings.get('invoice_address_asked', as_type=bool) or self.event.settings.get('invoice_name_required', as_type=bool):
return True
ask_names = self.event.settings.get('attendee_names_asked', as_type=bool)
for cp in positions:
if cp.item.get_asked_questions(questionnaire_type=Questionnaire.QuestionnaireType.POSITION_PURCHASE): # TODO(questionnaires) : use prefetched data
if (cp.item.ask_attendee_data and ask_names) or cp.item.questions.all():
return True
return False # nothing there to modify
@@ -1566,13 +1394,6 @@ class QuestionAnswer(models.Model):
elif self.checkoutsession:
return self.checkoutsession.event
@property
def container_type(self):
if self.orderposition_id or self.cartposition_id:
return Question.ContainerType.ORDERPOSITION
elif self.order_id or self.checkoutsession_id:
return Question.ContainerType.ORDER
def __str__(self):
return self.to_string(use_cached=True)
@@ -1628,12 +1449,6 @@ class QuestionAnswer(models.Model):
else:
return self.answer
def to_dependency_values(self):
if self.question.type in (Question.TYPE_CHOICE, Question.TYPE_CHOICE_MULTIPLE):
return [o.identifier for o in self.options.all()]
elif self.question.type in (Question.TYPE_BOOLEAN, Question.TYPE_COUNTRYCODE):
return self.answer
def save(self, *args, **kwargs):
if self.orderposition and self.cartposition:
raise ValueError('QuestionAnswer cannot be linked to an order and a cart position at the same time.')
@@ -1646,10 +1461,6 @@ class QuestionAnswer(models.Model):
self.orderposition.order.touch()
super().delete(**kwargs)
def set_file(self, new_file):
self.file.save(os.path.basename(new_file.name), new_file, save=False)
self.answer = 'file://' + self.file.name
class RoundingCorrectionMixin:
@@ -1666,7 +1477,7 @@ class RoundingCorrectionMixin:
return self.gross_price_before_rounding - self.tax_value_before_rounding
class AbstractPosition(AnswerableMixin, RoundingCorrectionMixin, models.Model):
class AbstractPosition(RoundingCorrectionMixin, models.Model):
"""
A position can either be one line of an order or an item placed in a cart.
@@ -1780,34 +1591,56 @@ class AbstractPosition(AnswerableMixin, RoundingCorrectionMixin, models.Model):
def meta_info_data(self, d):
self.meta_info = json.dumps(d)
def get_questionnaire_renderer(self, questionnaire_type, sales_channel):
def cache_answers(self, all=True):
"""
Creates a new property on the object:
question_data: a list of QuestionnaireRow objects, extended by an 'answer' property
Creates two properties on the object.
(1) answ: a dictionary of question.id → answer string
(2) questions: a list of Question objects, extended by an 'answer' property
"""
self.answ = {}
for a in getattr(self, 'answerlist', self.answers.all()): # use prefetch_related cache from get_cart
self.answ[a.question_id] = a
# We need to clone our question objects, otherwise we will override the cached
# answers of other items in the same cart if the question objects have been
# selected via prefetch_related
cache_key = 'relevant_questionnaires' + (f'_{questionnaire_type}' if questionnaire_type else '')
if (questionnaires := getattr(self.item, cache_key, None)) is not None:
qrows = list(copy.copy(qc) for qq in questionnaires for qc in qq.rows.all())
if not all:
if hasattr(self.item, 'questions_to_ask'):
questions = list(copy.copy(q) for q in self.item.questions_to_ask)
else:
questions = list(copy.copy(q) for q in self.item.questions.filter(ask_during_checkin=False,
hidden=False))
else:
qrows = list(self.item.get_asked_questions(questionnaire_type=questionnaire_type, sales_channel=sales_channel))
return QuestionnaireRenderer(qrows, self.system_answers, self.answers.all())
questions = list(copy.copy(q) for q in self.item.questions.all())
@cached_property
def system_answers(self):
return {
"@attendee_name_parts": self.attendee_name,
"@attendee_email": self.attendee_email,
"@company": self.company,
"@street": self.street,
"@zipcode": self.zipcode,
"@city": self.city,
"@state": self.state,
"@country": str(self.country) if self.country else None,
question_cache = {
q.pk: q for q in questions
}
def question_is_visible(parentid, qvals):
if parentid not in question_cache:
return False
parentq = question_cache[parentid]
if parentq.dependency_question_id and not question_is_visible(parentq.dependency_question_id, parentq.dependency_values):
return False
if parentid not in self.answ:
return False
return (
('True' in qvals and self.answ[parentid].answer == 'True')
or ('False' in qvals and self.answ[parentid].answer == 'False')
or (any(qval in [o.identifier for o in self.answ[parentid].options.all()] for qval in qvals))
)
self.questions = []
for q in questions:
if q.id in self.answ:
q.answer = self.answ[q.id]
q.answer.question = q # cache object
else:
q.answer = ""
if not q.dependency_question_id or question_is_visible(q.dependency_question_id, q.dependency_values):
self.questions.append(q)
@property
def net_price(self):
return self.price - self.tax_value
@@ -1819,21 +1652,20 @@ class AbstractPosition(AnswerableMixin, RoundingCorrectionMixin, models.Model):
else self.variation.quotas.filter(subevent=self.subevent))
def save(self, *args, **kwargs):
def ensure_updated(fieldname):
if 'update_fields' in kwargs:
kwargs['update_fields'] = {fieldname}.union(kwargs['update_fields'])
if 'attendee_name_parts' in kwargs.get('update_fields', set()):
ensure_updated('attendee_name_cached')
update_fields = kwargs.get('update_fields', set())
if 'attendee_name_parts' in update_fields:
kwargs['update_fields'] = {'attendee_name_cached'}.union(kwargs['update_fields'])
name = self.attendee_name
if name != self.attendee_name_cached:
self.attendee_name_cached = name
ensure_updated('attendee_name_cached')
if 'update_fields' in kwargs:
kwargs['update_fields'] = {'attendee_name_cached'}.union(kwargs['update_fields'])
if self.attendee_name_parts is None:
self.attendee_name_parts = {}
ensure_updated('attendee_name_parts')
if 'update_fields' in kwargs:
kwargs['update_fields'] = {'attendee_name_parts'}.union(kwargs['update_fields'])
super().save(*args, **kwargs)
@property
@@ -2909,7 +2741,7 @@ class OrderPosition(AbstractPosition):
positions = list(
self.order.positions.all().annotate(
has_checkin=Exists(Checkin.objects.filter(position_id=OuterRef('pk'), list__consider_tickets_used=True))
).select_related('item').prefetch_related('item__questionnaires')
).select_related('item').prefetch_related('item__questions')
)
if not self.event.settings.allow_modifications_after_checkin:
for cp in positions:
@@ -2919,7 +2751,7 @@ class OrderPosition(AbstractPosition):
ask_names = self.event.settings.get('attendee_names_asked', as_type=bool)
for cp in positions:
if cp.pk == self.pk or cp.addon_to_id == self.pk:
if cp.item.questionnaires.all(): # TODO(questionnaires) : filter to only QuestionnaireType.POSITION_PURCHASE
if (cp.item.ask_attendee_data and ask_names) or cp.item.questions.all():
return True
return False # nothing there to modify
@@ -3347,7 +3179,7 @@ class Transaction(models.Model):
return self.tax_value_includes_rounding_correction * self.count
class CheckoutSession(OrderLevelAnswerableMixin, models.Model):
class CheckoutSession(models.Model):
"""
A checkout session optionally bundles cart positions with additional information. This is historically
not required in pretix and currently only used in the Storefront API.
+3 -3
View File
@@ -72,7 +72,7 @@ from pretix.helpers.countries import CachedCountries
from pretix.helpers.format import format_map
from pretix.helpers.money import DecimalTextInput
from pretix.multidomain.urlreverse import eventreverse_absolute
from pretix.presale.views import get_cart_positions
from pretix.presale.views import get_cart
from pretix.presale.views.cart import cart_session, get_or_create_cart_id
logger = logging.getLogger(__name__)
@@ -1165,7 +1165,7 @@ class FreeOrderProvider(BasePaymentProvider):
def is_allowed(self, request: HttpRequest, total: Decimal=None) -> bool:
from .services.cart import get_fees
cart = get_cart_positions(request)
cart = get_cart(request)
try:
fees = get_fees(event=request.event, request=request,
@@ -1433,7 +1433,7 @@ class GiftCardPayment(BasePaymentProvider):
for p in cs.get('payments', [])
if p.get('info_data', {}).get('gift_card')
]
positions = get_cart_positions(request)
positions = get_cart(request)
testmode = self.event.testmode
else:
used_cards = []
+49 -23
View File
@@ -83,7 +83,6 @@ from pretix.base.signals import layout_image_variables, layout_text_variables
from pretix.base.templatetags.money import money_filter
from pretix.base.templatetags.phone_format import phone_format
from pretix.helpers.daterange import datetimerange
from pretix.helpers.models import find_first_with_cache, is_prefetched
from pretix.helpers.reportlab import (
ThumbnailingImageReader, register_ttf_font_if_new, reshaper,
)
@@ -386,14 +385,13 @@ DEFAULT_VARIABLES = OrderedDict((
str(p) for p in generate_compressed_addon_list(op, order, ev)
])
}),
# TODO(questionnaires) - re-add this once PR 6778 or similar is merged
# ("checked_in_addons", {
# "label": _("List of Checked-In Add-Ons"),
# "editor_sample": _("Add-on 1\n2x Add-on 2"),
# "evaluate": lambda op, order, ev: "\n".join([
# str(p) for p in generate_compressed_addon_list(op, order, ev, only_checked_in=True)
# ])
# }),
("checked_in_addons", {
"label": _("List of Checked-In Add-Ons"),
"editor_sample": _("Add-on 1\n2x Add-on 2"),
"evaluate": lambda op, order, ev: "\n".join([
str(p) for p in generate_compressed_addon_list(op, order, ev, only_checked_in=True)
])
}),
("organizer", {
"label": _("Organizer name"),
"editor_sample": _("Event organizer company"),
@@ -557,9 +555,23 @@ DEFAULT_IMAGES = OrderedDict([])
@receiver(layout_image_variables, dispatch_uid="pretix_base_layout_image_variables_questions")
def images_from_questions(sender, *args, **kwargs):
def get_answer(op, order, event, question_id, etag):
a = find_first_with_cache(op.answers, question_id=question_id)
if a is None and op.addon_to:
a = find_first_with_cache(op.addon_to.answers, question_id=question_id)
a = None
if op.addon_to:
if 'answers' in getattr(op.addon_to, '_prefetched_objects_cache', {}):
try:
a = [a for a in op.addon_to.answers.all() if a.question_id == question_id][0]
except IndexError:
pass
else:
a = op.addon_to.answers.filter(question_id=question_id).first()
if 'answers' in getattr(op, '_prefetched_objects_cache', {}):
try:
a = [a for a in op.answers.all() if a.question_id == question_id][0]
except IndexError:
pass
else:
a = op.answers.filter(question_id=question_id).first() or a
if not a or not a.file or not any(a.file.name.lower().endswith(e) for e in settings.FILE_UPLOAD_EXTENSIONS_QUESTION_IMAGE):
return None
@@ -569,11 +581,11 @@ def images_from_questions(sender, *args, **kwargs):
return a.file
d = {}
for q in sender.positiondatafields:
for q in sender.questions.all():
if q.type != Question.TYPE_FILE:
continue
d['question_{}'.format(q.identifier)] = {
'label': _('Data field: {question}').format(question=q.internal_name),
'label': _('Question: {question}').format(question=q.question),
'evaluate': partial(get_answer, question_id=q.pk, etag=False),
'etag': partial(get_answer, question_id=q.pk, etag=True),
}
@@ -583,9 +595,23 @@ def images_from_questions(sender, *args, **kwargs):
@receiver(layout_text_variables, dispatch_uid="pretix_base_layout_text_variables_questions")
def variables_from_questions(sender, *args, **kwargs):
def get_answer(op, order, event, question_id):
a = find_first_with_cache(op.answers, question_id=question_id)
if a is None and op.addon_to:
a = find_first_with_cache(op.addon_to.answers, question_id=question_id)
a = None
if op.addon_to:
if 'answers' in getattr(op.addon_to, '_prefetched_objects_cache', {}):
try:
a = [a for a in op.addon_to.answers.all() if a.question_id == question_id][0]
except IndexError:
pass
else:
a = op.addon_to.answers.filter(question_id=question_id).first()
if 'answers' in getattr(op, '_prefetched_objects_cache', {}):
try:
a = [a for a in op.answers.all() if a.question_id == question_id][0]
except IndexError:
pass
else:
a = op.answers.filter(question_id=question_id).first() or a
if not a:
return ""
@@ -593,18 +619,18 @@ def variables_from_questions(sender, *args, **kwargs):
return a.to_string_i18n()
d = {}
for q in sender.positiondatafields:
for q in sender.questions.all():
if q.type == Question.TYPE_FILE:
continue
d['question_{}'.format(q.identifier)] = {
'label': _('Data field: {question}').format(question=q.internal_name),
'editor_sample': _('<Answer: {question}>').format(question=q.internal_name),
'label': _('Question: {question}').format(question=q.question),
'editor_sample': _('<Answer: {question}>').format(question=q.question),
'evaluate': partial(get_answer, question_id=q.pk),
'migrate_from': 'question_{}'.format(q.pk)
}
d['question_{}'.format(q.pk)] = {
'label': _('Data field: {question}').format(question=q.internal_name),
'editor_sample': _('<Answer: {question}>').format(question=q.internal_name),
'label': _('Question: {question}').format(question=q.question),
'editor_sample': _('<Answer: {question}>').format(question=q.question),
'evaluate': partial(get_answer, question_id=q.pk),
'hidden': True,
}
@@ -750,7 +776,7 @@ def get_program_times(op: OrderPosition, ev: Event):
def generate_compressed_addon_list(op, order, event, only_checked_in=False):
itemcount = defaultdict(int)
addon_qs = (
op.addons.all() if is_prefetched(op.addons)
op.addons.all() if 'addons' in getattr(op, '_prefetched_objects_cache', {})
else op.addons.select_related('item', 'variation')
)
if only_checked_in:
+1 -2
View File
@@ -1410,11 +1410,10 @@ class CartManager:
for k, v in self._widget_data.items():
if not k.startswith('question-'):
continue
# TODO(questionnaires) - switch to QuestionnaireRow
q = cp.item.questions.filter(ask_during_checkin=False, identifier__iexact=k[9:]).first()
if q:
try:
cp._answers[q] = q.clean_answer(v) # TODO(questionnaires) - switch to row.clean_answer
cp._answers[q] = q.clean_answer(v)
except ValidationError:
pass
+35 -59
View File
@@ -35,7 +35,6 @@ import logging
import os
from datetime import datetime, timedelta, timezone
from functools import partial, reduce
from typing import List
import dateutil
import dateutil.parser
@@ -43,7 +42,7 @@ from dateutil.tz import datetime_exists
from django.core.files import File
from django.db import IntegrityError
from django.db.models import (
BooleanField, Case, Count, Exists, ExpressionWrapper, F, IntegerField, Max, Min,
BooleanField, Case, Count, ExpressionWrapper, F, IntegerField, Max, Min,
OuterRef, Q, Subquery, TextField, Value, When,
)
from django.db.models.functions import Coalesce, TruncDate
@@ -56,9 +55,8 @@ from django_scopes import scope, scopes_disabled
from pretix.base.models import (
Checkin, CheckinList, Device, Event, Gate, Item, ItemVariation, Order,
OrderPosition, Questionnaire, QuestionnaireRow, QuestionOption,
OrderPosition, QuestionOption,
)
from pretix.base.models.orders import QuestionAnswer, QuestionnaireRenderer
from pretix.base.signals import checkin_created, periodic_task
from pretix.helpers import OF_SELF
from pretix.helpers.database import conditional_atomic
@@ -863,10 +861,10 @@ class CheckInError(Exception):
class RequiredQuestionsError(Exception):
def __init__(self, msg, code, questionnaire_rows: List[QuestionnaireRow]):
def __init__(self, msg, code, questions):
self.msg = msg
self.code = code
self.questionnaire_rows = questionnaire_rows
self.questions = questions
super().__init__(msg)
@@ -879,13 +877,12 @@ class RequiredMediaExchangeError(Exception):
super().__init__(msg)
def _save_answers(op, existing_answer_objects, given_answers):
# used by perform_checkin to store `answers`, as well as by CartManager to store widget_data
def _save_answers(op, answers, given_answers):
def _create_answer(question, answer):
try:
return op.answers.create(question=question, answer=answer)
except IntegrityError:
# Since we prefetch answers in _checkin_list_position_queryset, there's a possible race condition
# Since we prefill ``field.answer`` at form creation time, there's a possible race condition
# here if the user submits their scan a second time while the first one is still running,
# thus leading to duplicate QuestionAnswer objects. Since Django doesn't support UPSERT, the "proper"
# fix would be a transaction with select_for_update(), or at least fetching using get_or_create here
@@ -900,14 +897,14 @@ def _save_answers(op, existing_answer_objects, given_answers):
written = False
for q, a in given_answers.items():
if not a:
if q.id in existing_answer_objects:
if q in answers:
written = True
existing_answer_objects[q.id].delete()
answers[q].delete()
else:
continue
if isinstance(a, QuestionOption):
if q.id in existing_answer_objects:
qa = existing_answer_objects[q.id]
if q in answers:
qa = answers[q]
qa.answer = str(a.answer)
qa.save()
written = True
@@ -916,8 +913,8 @@ def _save_answers(op, existing_answer_objects, given_answers):
qa = _create_answer(question=q, answer=str(a.answer))
qa.options.add(a)
elif isinstance(a, list):
if q.id in existing_answer_objects:
qa = existing_answer_objects[q.id]
if q in answers:
qa = answers[q]
qa.answer = ", ".join([str(o) for o in a])
qa.save()
written = True
@@ -926,16 +923,17 @@ def _save_answers(op, existing_answer_objects, given_answers):
qa = _create_answer(question=q, answer=", ".join([str(o) for o in a]))
qa.options.add(*a)
elif isinstance(a, File):
if q.id in existing_answer_objects:
qa = existing_answer_objects[q.id]
if q in answers:
qa = answers[q]
else:
qa = _create_answer(question=q, answer=str(a))
qa.set_file(a)
qa.file.save(os.path.basename(a.name), a, save=False)
qa.answer = 'file://' + qa.file.name
qa.save()
written = True
else:
if q.id in existing_answer_objects:
qa = existing_answer_objects[q.id]
if q in answers:
qa = answers[q]
qa.answer = str(a)
qa.save()
else:
@@ -943,31 +941,23 @@ def _save_answers(op, existing_answer_objects, given_answers):
written = True
if written:
op.answers._remove_prefetched_objects()
prefetched_objects_cache = getattr(op, '_prefetched_objects_cache', {})
if 'answers' in prefetched_objects_cache:
del prefetched_objects_cache['answers']
def _get_checkin_questions(op):
return list(
QuestionnaireRow.objects.filter(
~Exists(QuestionAnswer.objects.filter(orderposition=op, question=OuterRef('user_datafield'))),
questionnaire__type=Questionnaire.QuestionnaireType.POSITION_CHECKIN,
questionnaire__items__in=[op.item_id],
).select_related('user_datafield', 'questionnaire')
)
def perform_checkin(op: OrderPosition, clist: CheckinList, given_answers: list, force=False,
def perform_checkin(op: OrderPosition, clist: CheckinList, given_answers: dict, force=False,
ignore_unpaid=False, nonce=None, datetime=None, questions_supported=True,
user=None, auth=None, canceled_supported=False, type=Checkin.TYPE_ENTRY,
raw_barcode=None, raw_source_type=None, from_revoked_secret=False, simulate=False,
gate=None, reusable_medium=None, given_system_answers=None):
gate=None, reusable_medium=None):
"""
Create a checkin for this particular order position and check-in list. Fails with CheckInError if the check in is
not valid at this time.
:param op: The order position to check in
:param clist: The order position to check in
:param given_answers: A dictionary of data field objects mapped to validated, given answers
:param given_answers: A dictionary of questions mapped to validated, given answers
:param force: When set to True, this will succeed even when the position is already checked in or when required
questions are not filled out.
:param ignore_unpaid: When set to True, this will succeed even when the order is unpaid.
@@ -979,8 +969,6 @@ def perform_checkin(op: OrderPosition, clist: CheckinList, given_answers: list,
:param reusable_medium: The medium that is available for an exchange
"""
assert isinstance(given_answers, list) or (isinstance(given_answers, dict) and not given_answers) # given_answers must be list (or empty dict, for plugin compatibility)
# !!!!!!!!!
# Update doc/images/checkin_online.puml if you make substantial changes here!
# !!!!!!!!!
@@ -1044,30 +1032,18 @@ def perform_checkin(op: OrderPosition, clist: CheckinList, given_answers: list,
)
# Do this outside of transaction so it is saved even if the checkin fails for some other reason
if not hasattr(op.item, '_checkin_questions'):
op.item._checkin_questions = _get_checkin_questions(op)
checkin_questions = list(
clist.event.questions.filter(ask_during_checkin=True, items__in=[op.item_id])
)
require_answers = []
if type != Checkin.TYPE_EXIT and op.item._checkin_questions:
answered_now = set()
if given_system_answers:
for k, v in given_system_answers.items():
answered_now.add(f'@{k}')
setattr(op, k, v)
if not simulate:
op.save(update_fields=given_system_answers.keys())
qrenderer = QuestionnaireRenderer(qrows=[], system_answers=op.system_answers, answerlist=op.answers.all())
answered = dict(qrenderer.answer_cache)
for answ in given_answers:
answered[answ['question'].id] = answ.get('options') or answ['answer']
answered_now.add(answ['question'].id)
for q in op.item._checkin_questions:
k = q.system_datafield or q.user_datafield_id
# require answers if: answer (stored or new) is empty, and the question is either required or wasn't answered right now
# this means: a required question needs a non-empty answer; a non-required questions needs either an non-empty answer, or needs to be answered (even empty) right now
if answered.get(k) in (None, [], False, '') and (q.required or k not in answered_now):
if type != Checkin.TYPE_EXIT and checkin_questions:
answers = {a.question: a for a in op.answers.all()}
for q in checkin_questions:
if q not in given_answers and q not in answers:
require_answers.append(q)
if not simulate:
op.set_answers(given_answers, delete_missing=False)
_save_answers(op, answers, given_answers)
with conditional_atomic(not simulate):
# Lock order positions, if it is an entry. We don't need it for exits, as a race condition wouldn't be problematic
@@ -1134,7 +1110,7 @@ def perform_checkin(op: OrderPosition, clist: CheckinList, given_answers: list,
raise RequiredQuestionsError(
_('You need to answer questions to complete this check-in.'),
'incomplete',
questionnaire_rows=require_answers,
require_answers
)
required_media_policy = op.item.media_policy
@@ -1197,7 +1173,7 @@ def perform_checkin(op: OrderPosition, clist: CheckinList, given_answers: list,
'forced': force or op.order.status != Order.STATUS_PAID,
'datetime': dt,
'type': type,
'answers': {str(answ['question'].id): answ.get('option_identifiers') or answ['answer'] for answ in given_answers},
'answers': {k.pk: str(v) for k, v in given_answers.items()},
'list': clist.pk
}, user=user, auth=auth)
checkin_created.send(op.order.event, checkin=ci)
+3 -3
View File
@@ -279,13 +279,13 @@ def build_invoice(invoice: Invoice) -> Invoice:
).select_related(
'question'
).order_by(
'question__internal_name',
'question__position',
'question__id'
)
for answ in answers_qs:
desc += "<br />{}{} {}".format(
answ.question.print_on_invoice_label,
"" if str(answ.question.print_on_invoice_label).endswith("?") else ":",
answ.question.question,
"" if str(answ.question.question).endswith("?") else ":",
answ.to_string_i18n()
)
+114 -7
View File
@@ -379,12 +379,99 @@ DEFAULTS = {
)
},
# 'system_question_order': { # TODO(questionnaires) - remove this
# 'default': {},
# 'type': dict,
# 'serializer_class': serializers.DictField,
# 'serializer_kwargs': lambda: dict(read_only=True, allow_empty=True),
# },
'system_question_order': {
'default': {},
'type': dict,
'serializer_class': serializers.DictField,
'serializer_kwargs': lambda: dict(read_only=True, allow_empty=True),
},
'attendee_names_asked': {
'default': 'True',
'type': bool,
'form_class': forms.BooleanField,
'serializer_class': serializers.BooleanField,
'form_kwargs': dict(
label=_("Ask for attendee names"),
help_text=_("Ask for a name for all personalized tickets."),
)
},
'attendee_names_required': {
'default': 'False',
'type': bool,
'form_class': forms.BooleanField,
'serializer_class': serializers.BooleanField,
'form_kwargs': dict(
label=_("Require attendee names"),
help_text=_("Require customers to fill in the names of all attendees."),
widget=forms.CheckboxInput(attrs={'data-checkbox-dependency': '#id_settings-attendee_names_asked'}),
)
},
'attendee_emails_asked': {
'default': 'False',
'type': bool,
'form_class': forms.BooleanField,
'serializer_class': serializers.BooleanField,
'form_kwargs': dict(
label=_("Ask for email addresses per ticket"),
help_text=_("Normally, pretix asks for one email address per order and the order confirmation will be sent "
"only to that email address. If you enable this option, the system will additionally ask for "
"individual email addresses for every personalized ticket. This might be useful if you want to "
"obtain individual addresses for every attendee even in case of group orders. However, "
"pretix will send the order confirmation by default only to the one primary email address, not to "
"the per-attendee addresses. You can however enable this in the email settings."),
)
},
'attendee_emails_required': {
'default': 'False',
'type': bool,
'form_class': forms.BooleanField,
'serializer_class': serializers.BooleanField,
'form_kwargs': dict(
label=_("Require email addresses per ticket"),
help_text=_("Require customers to fill in individual email addresses for all personalized tickets. See the "
"above option for more details. One email address for the order confirmation will always be "
"required regardless of this setting."),
widget=forms.CheckboxInput(attrs={'data-checkbox-dependency': '#id_settings-attendee_emails_asked'}),
)
},
'attendee_company_asked': {
'default': 'False',
'type': bool,
'form_class': forms.BooleanField,
'serializer_class': serializers.BooleanField,
'form_kwargs': dict(
label=_("Ask for company per ticket"),
)
},
'attendee_company_required': {
'default': 'False',
'type': bool,
'form_class': forms.BooleanField,
'serializer_class': serializers.BooleanField,
'form_kwargs': dict(
label=_("Require company per ticket"),
widget=forms.CheckboxInput(attrs={'data-checkbox-dependency': '#id_settings-attendee_company_asked'}),
)
},
'attendee_addresses_asked': {
'default': 'False',
'type': bool,
'form_class': forms.BooleanField,
'serializer_class': serializers.BooleanField,
'form_kwargs': dict(
label=_("Ask for postal addresses per ticket"),
)
},
'attendee_addresses_required': {
'default': 'False',
'type': bool,
'form_class': forms.BooleanField,
'serializer_class': serializers.BooleanField,
'form_kwargs': dict(
label=_("Require postal addresses per ticket"),
widget=forms.CheckboxInput(attrs={'data-checkbox-dependency': '#id_settings-attendee_addresses_asked'}),
)
},
'order_email_asked_twice': {
'default': 'False',
'type': bool,
@@ -3351,6 +3438,19 @@ Your {organizer} team""")) # noqa: W291
"how to obtain a voucher code.")
)
},
'attendee_data_explanation_text': {
'default': '',
'type': LazyI18nString,
'serializer_class': I18nField,
'form_class': I18nFormField,
'form_kwargs': dict(
label=_("Attendee data explanation"),
widget=I18nMarkdownTextarea,
widget_kwargs={'attrs': {'rows': '2'}},
help_text=_("This text will be shown above the questions asked for every personalized product. You can use it e.g. to explain "
"why you need information from them.")
)
},
'checkout_success_text': {
'default': '',
'type': LazyI18nString,
@@ -3956,7 +4056,6 @@ PERSON_NAME_SCHEMES = OrderedDict([
'_scheme': 'salutation_title_given_family_degree',
},
}),
# If new schemes add new fields, update QuestionnaireRow._name_schemes_all_fields
])
DEFAULTS['name_scheme']['serializer_kwargs']['choices'] = ((k, k) for k in PERSON_NAME_SCHEMES)
@@ -4073,6 +4172,14 @@ def validate_event_settings(event, settings_dict):
raise ValidationError({
'locale': _('Your default locale must also be enabled for your event (see box above).')
})
if settings_dict.get('attendee_names_required') and not settings_dict.get('attendee_names_asked'):
raise ValidationError({
'attendee_names_required': _('You cannot require specifying attendee names if you do not ask for them.')
})
if settings_dict.get('attendee_emails_required') and not settings_dict.get('attendee_emails_asked'):
raise ValidationError({
'attendee_emails_required': _('You have to ask for attendee emails if you want to make them required.')
})
if settings_dict.get('invoice_address_required') and not settings_dict.get('invoice_address_asked'):
raise ValidationError({
'invoice_address_required': _('You have to ask for invoice addresses if you want to make them required.')
+45 -33
View File
@@ -27,7 +27,7 @@ from decimal import Decimal
from django import forms
from django.core.files.uploadedfile import UploadedFile
from django.db import IntegrityError
from django.db.models import Prefetch, Q, QuerySet
from django.db.models import Prefetch, QuerySet
from django.utils.functional import cached_property
from django.utils.timezone import make_aware
@@ -37,19 +37,17 @@ from pretix.base.forms.questions import (
)
from pretix.base.models import (
CartPosition, InvoiceAddress, OrderPosition, Question, QuestionAnswer,
Questionnaire, QuestionnaireRow, QuestionOption,
QuestionOption,
)
from pretix.base.models.customers import AttendeeProfile
from pretix.base.models.orders import CheckoutSession, Order
from pretix.presale.signals import contact_form_fields_overrides
from pretix.presale.views import prefetch_relevant_questionnaires
class BaseQuestionsViewMixin:
order_form_class = OrderLevelQuestionsForm
orderposition_form_class = TicketLevelQuestionsForm
all_optional = False
only_user_visible = False
@cached_property
def _positions_for_questions(self):
@@ -103,23 +101,26 @@ class BaseQuestionsViewMixin:
cartpos=cartpos,
orderpos=orderpos,
all_optional=self.all_optional,
only_user_visible=self.only_user_visible,
data=(self.request.POST if self.request.method == 'POST' else None),
files=(self.request.FILES if self.request.method == 'POST' else None),
**kwargs
)
form.pos = cartpos or orderpos
form.show_copy_answers_to_addon_button = form.pos.addon_to and (
# TODO(questionnaires) - prefetch this
set(qc.form_field_name for qc in form.pos.addon_to.item.get_asked_questions(questionnaire_type=Questionnaire.QuestionnaireType.POSITION_PURCHASE))
& set(qc.form_field_name for qc in form.pos.item.get_asked_questions(questionnaire_type=Questionnaire.QuestionnaireType.POSITION_PURCHASE))
set(form.pos.addon_to.item.questions.all()) & set(form.pos.item.questions.all()) or
(form.pos.addon_to.item.ask_attendee_data and form.pos.item.ask_attendee_data and (
self.request.event.settings.attendee_names_asked or
self.request.event.settings.attendee_emails_asked or
self.request.event.settings.attendee_company_asked or
self.request.event.settings.attendee_addresses_asked
))
)
override_sets = self.get_question_override_sets(cr, idx)
for overrides in override_sets:
for question_name, question_field in form.fields.items():
if hasattr(question_field, 'datafield'):
src = overrides.get(question_field.datafield.identifier)
if hasattr(question_field, 'question'):
src = overrides.get(question_field.question.identifier)
else:
src = overrides.get(question_name)
if not src:
@@ -167,23 +168,23 @@ class BaseQuestionsViewMixin:
for k, v in self.order_questions_form.cleaned_data.items():
if k.startswith('question_'):
field = self.order_questions_form.fields[k]
if hasattr(field, 'answer_object'):
if hasattr(field, 'answer'):
# We already have a cached answer object, so we don't
# have to create a new one
if v == '' or v is None or (isinstance(field, forms.FileField) and v is False) \
or (isinstance(v, QuerySet) and not v.exists()):
if field.answer_object.file:
field.answer_object.file.delete()
field.answer_object.delete()
if field.answer.file:
field.answer.file.delete()
field.answer.delete()
else:
self._save_to_answer(field, field.answer_object, v)
field.answer_object.save()
self._save_to_answer(field, field.answer, v)
field.answer.save()
elif v != '' and v is not None:
self._upsert_answer(
field, v,
checkoutsession=checkoutsession,
order=order,
question=field.datafield,
question=field.question,
)
for form in self.forms:
@@ -226,26 +227,26 @@ class BaseQuestionsViewMixin:
form.pos.requested_valid_from = None
elif k.startswith('question_'):
field = form.fields[k]
if hasattr(field, 'answer_object'):
if hasattr(field, 'answer'):
# We already have a cached answer object, so we don't
# have to create a new one
if v == '' or v is None or (isinstance(field, forms.FileField) and v is False) \
or (isinstance(v, QuerySet) and not v.exists()):
if field.answer_object.file:
field.answer_object.file.delete()
field.answer_object.delete()
if field.answer.file:
field.answer.file.delete()
field.answer.delete()
else:
self._save_to_answer(field, field.answer_object, v)
field.answer_object.save()
self._save_to_answer(field, field.answer, v)
field.answer.save()
answer_dict = self._build_answer_dict(field, field.answer_object, k)
answer_dict = self._build_answer_dict(field, field.answer, k)
prof.store_answer(answer_dict)
elif v != '' and v is not None:
answer = self._upsert_answer(
field, v,
cartposition=cartposition,
orderposition=orderposition,
question=field.datafield,
question=field.question,
)
answer_dict = self._build_answer_dict(field, answer, k)
@@ -285,7 +286,7 @@ class BaseQuestionsViewMixin:
self._save_to_answer(field, answer, v)
answer.save()
except IntegrityError:
# Since we prefill ``field.answer_object`` at form creation time, there's a possible race condition
# Since we prefill ``field.answer`` at form creation time, there's a possible race condition
# here if the users submits their save request a second time while the first one is still running,
# thus leading to duplicate QuestionAnswer objects. Since Django doesn't support UPSERT, the "proper"
# fix would be a transaction with select_for_update(), or at least fetching using get_or_create here
@@ -314,7 +315,8 @@ class BaseQuestionsViewMixin:
answer.answer = value.answer
elif isinstance(field, forms.FileField):
if isinstance(value, UploadedFile):
answer.set_file(value)
answer.file.save(value.name, value)
answer.answer = 'file://' + value.name
else:
answer.answer = value
@@ -329,8 +331,8 @@ class BaseQuestionsViewMixin:
'field_name': k,
'field_label': str(field.label),
'value': answer_value,
'question_type': field.datafield.type,
'question_identifier': field.datafield.identifier,
'question_type': field.question.type,
'question_identifier': field.question.identifier,
}
@@ -346,17 +348,27 @@ class OrderQuestionsViewMixin(BaseQuestionsViewMixin):
@cached_property
def positions(self):
qqs = self.request.event.questions.all()
if self.only_user_visible:
type = Questionnaire.QuestionnaireType.POSITION_PURCHASE
else:
type = None
qqs = qqs.filter(ask_during_checkin=False, hidden=False, container_type=Question.ContainerType.ORDERPOSITION)
return list(self.order.positions.select_related(
'item', 'variation'
).prefetch_related(
Prefetch('answers',
QuestionAnswer.objects.prefetch_related('options'),
to_attr='answerlist'),
prefetch_relevant_questionnaires(self.order.sales_channel.identifier, type),
Prefetch('item__questions',
qqs.prefetch_related(
Prefetch('options', QuestionOption.objects.prefetch_related(Prefetch(
# This prefetch statement is utter bullshit, but it actually prevents Django from doing
# a lot of queries since ModelChoiceIterator stops trying to be clever once we have
# a prefetch lookup on this query...
'question',
Question.objects.none(),
to_attr='dummy'
)))
).select_related('dependency_question'),
to_attr='questions_to_ask')
))
@cached_property
-2
View File
@@ -26,7 +26,6 @@ from django.core import signing
from django.http import HttpResponseBadRequest, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.utils.html import format_html
logger = logging.getLogger(__name__)
@@ -61,7 +60,6 @@ def redir_view(request):
u = urllib.parse.urlparse(url)
return render(request, 'pretixbase/redirect.html', {
'hostname': u.hostname,
'bold_hostname': format_html("<strong>{}</strong>", u.hostname),
'url': url,
})
+11 -2
View File
@@ -639,6 +639,15 @@ class EventSettingsForm(EventSettingsValidationMixin, FormPlaceholderMixin, Sett
'event_calendar_future_only',
'frontpage_text',
'event_info_text',
'attendee_names_asked',
'attendee_names_required',
'attendee_emails_asked',
'attendee_emails_required',
'attendee_company_asked',
'attendee_company_required',
'attendee_addresses_asked',
'attendee_addresses_required',
'attendee_data_explanation_text',
'order_phone_asked',
'order_phone_required',
'checkout_phone_helptext',
@@ -1940,8 +1949,8 @@ class QuickSetupForm(I18nForm):
)
attendee_names_required = forms.BooleanField(
label=_("Require all attendees to fill in their names"),
help_text=_("By default, we will ask for names but not require them. You can turn this off completely by changing "
"the attendee data questionnaire."),
help_text=_("By default, we will ask for names but not require them. You can turn this off completely in the "
"settings."),
required=False
)
imprint_url = forms.URLField(
+9 -10
View File
@@ -728,7 +728,7 @@ class EventOrderExpertFilterForm(EventOrderFilterForm):
self.fields['quota'].widget.choices = self.fields['quota'].choices
for q in self.event.questions.all():
kwargs = {
"label": q.internal_name,
"label": q.question,
"required": False,
}
fname = 'question_{}'.format(q.pk)
@@ -887,30 +887,29 @@ class EventOrderExpertFilterForm(EventOrderFilterForm):
).distinct()
for q in self.event.questions.all():
if fdata.get(f'question_{q.pk}'):
ref = {'orderposition__order_id': OuterRef('pk')} if q.container_type == Question.ContainerType.ORDERPOSITION else {'order_id': OuterRef('pk')}
if q.type in (Question.TYPE_BOOLEAN, Question.TYPE_NUMBER):
answers = QuestionAnswer.objects.filter(
question_id=q.pk,
answer__exact=fdata.get(f'question_{q.pk}'),
**ref,
orderposition__order_id=OuterRef('pk'),
answer__exact=fdata.get(f'question_{q.pk}')
)
elif q.type in (Question.TYPE_DATE, Question.TYPE_TIME, Question.TYPE_DATETIME):
answers = QuestionAnswer.objects.filter(
question_id=q.pk,
answer__exact=str(fdata.get(f'question_{q.pk}')),
**ref,
orderposition__order_id=OuterRef('pk'),
answer__exact=str(fdata.get(f'question_{q.pk}'))
)
elif q.type in (Question.TYPE_CHOICE, Question.TYPE_CHOICE_MULTIPLE):
answers = QuestionAnswer.objects.filter(
question_id=q.pk,
options=fdata.get(f'question_{q.pk}'),
**ref,
orderposition__order_id=OuterRef('pk'),
options=fdata.get(f'question_{q.pk}')
)
else:
answers = QuestionAnswer.objects.filter(
question_id=q.pk,
answer__iexact=fdata.get(f'question_{q.pk}'),
**ref,
orderposition__order_id=OuterRef('pk'),
answer__iexact=fdata.get(f'question_{q.pk}')
)
qs = qs.annotate(**{f'q_{q.pk}': Exists(answers)}).filter(**{f'q_{q.pk}': True})
+82 -58
View File
@@ -60,13 +60,12 @@ from pretix.base.models import (
Item, ItemCategory, ItemProgramTime, ItemVariation, Question,
QuestionOption, Quota,
)
from pretix.base.models.items import (
ItemAddOn, ItemBundle, ItemMetaValue, Questionnaire,
)
from pretix.base.models.items import ItemAddOn, ItemBundle, ItemMetaValue
from pretix.base.signals import item_copy_data
from pretix.control.forms import (
ButtonGroupRadioSelect, ExtFileField, SalesChannelCheckboxSelectMultiple,
SplitDateTimeField, SplitDateTimePickerWidget,
ButtonGroupRadioSelect, ExtFileField, ItemMultipleChoiceField,
SalesChannelCheckboxSelectMultiple, SplitDateTimeField,
SplitDateTimePickerWidget,
)
from pretix.control.forms.widgets import Select2, Select2ItemVarMulti
from pretix.helpers.models import modelcopy
@@ -146,16 +145,61 @@ class CategoryForm(I18nModelForm):
class QuestionForm(I18nModelForm):
question = I18nFormField(
label=_("Question"),
widget_kwargs={'attrs': {'rows': 2}},
widget=I18nTextarea
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.instance.container_type != Question.ContainerType.ORDERPOSITION:
if self.instance.container_type == Question.ContainerType.ORDERPOSITION:
self.fields['items'].queryset = self.instance.event.items.all()
self.fields['items'].required = True
else:
del self.fields['items']
del self.fields['ask_during_checkin']
del self.fields['show_during_checkin']
del self.fields['print_on_invoice']
del self.fields['print_on_invoice_label']
else:
self.fields['print_on_invoice_label'].widget.attrs['data-display-dependency'] = '#id_print_on_invoice'
self.fields['print_on_invoice_label'].widget.attrs['rows'] = '2'
self.fields['dependency_question'].widget.attrs['data-container-type'] = self.instance.container_type
self.fields['dependency_question'].queryset = self.instance.event.questions.filter(
type__in=(Question.TYPE_BOOLEAN, Question.TYPE_CHOICE, Question.TYPE_CHOICE_MULTIPLE),
ask_during_checkin=False,
container_type=self.instance.container_type,
)
if self.instance.pk:
self.fields['dependency_question'].queryset = self.fields['dependency_question'].queryset.exclude(
pk=self.instance.pk
)
self.fields['identifier'].required = False
self.fields['dependency_values'].required = False
self.fields['help_text'].widget.attrs['rows'] = 3
def clean_dependency_values(self):
val = self.data.getlist('dependency_values')
return val
def clean_dependency_question(self):
dep = val = self.cleaned_data.get('dependency_question')
if dep:
if dep.ask_during_checkin:
raise ValidationError(_('Question cannot depend on a question asked during check-in.'))
seen_ids = {self.instance.pk} if self.instance else set()
while dep:
if dep.pk in seen_ids:
raise ValidationError(_('Circular dependency between questions detected.'))
seen_ids.add(dep.pk)
dep = dep.dependency_question
return val
def clean_ask_during_checkin(self):
val = self.cleaned_data.get('ask_during_checkin')
if val and self.cleaned_data.get('type') in Question.ASK_DURING_CHECKIN_UNSUPPORTED:
raise ValidationError(_('This type of question cannot be asked during check-in.'))
return val
def clean_show_during_checkin(self):
val = self.cleaned_data.get('show_during_checkin')
@@ -188,12 +232,18 @@ class QuestionForm(I18nModelForm):
model = Question
localized_fields = '__all__'
fields = [
'internal_name',
'question',
'help_text',
'type',
'required',
'ask_during_checkin',
'show_during_checkin',
'hidden',
'identifier',
'items',
'dependency_question',
'dependency_values',
'print_on_invoice',
'print_on_invoice_label',
'valid_number_min',
'valid_number_max',
'valid_datetime_min',
@@ -209,11 +259,17 @@ class QuestionForm(I18nModelForm):
'valid_datetime_max': SplitDateTimePickerWidget(without_seconds=True),
'valid_date_min': DatePickerWidget(),
'valid_date_max': DatePickerWidget(),
'items': forms.CheckboxSelectMultiple(
attrs={'class': 'scrolling-multiple-choice'}
),
'dependency_values': forms.SelectMultiple,
'help_text': I18nMarkdownTextarea,
}
field_classes = {
'valid_datetime_min': SplitDateTimeField,
'valid_datetime_max': SplitDateTimeField,
'items': ItemMultipleChoiceField,
'dependency_question': SafeModelChoiceField,
}
@@ -391,20 +447,13 @@ class ItemCreateForm(I18nModelForm):
help_text=_('Select this option e.g. for t-shirts that come in multiple sizes. '
'You can select the variations in the next step.'),
required=False)
questionnaires = SafeModelMultipleChoiceField(
queryset=Questionnaire.objects.none(),
required=False,
label=_('Questionnaires'),
widget=forms.CheckboxSelectMultiple(attrs={
'class': 'scrolling-multiple-choice'
}),
)
def __init__(self, *args, **kwargs):
self.event = kwargs['event']
self.user = kwargs.pop('user')
kwargs.setdefault('initial', {})
kwargs['initial'].setdefault('admission', True)
kwargs['initial'].setdefault('personalized', True)
super().__init__(*args, **kwargs)
self.fields['category'].queryset = self.instance.event.categories.all()
@@ -420,8 +469,6 @@ class ItemCreateForm(I18nModelForm):
)
self.fields['category'].widget.choices = self.fields['category'].choices
self.fields['questionnaires'].queryset = self.instance.event.questionnaires.filter(type__startswith='position_')
self.fields['tax_rule'].queryset = self.instance.event.tax_rules.all()
change_decimal_field(self.fields['default_price'], self.instance.event.currency)
self.fields['copy_from'] = forms.ModelChoiceField(
@@ -528,18 +575,10 @@ class ItemCreateForm(I18nModelForm):
self.instance.picture.save(os.path.basename(src.picture.name), src.picture)
self.instance.position = (self.event.items.aggregate(p=Max('position'))['p'] or 0) + 1
if not self.instance.admission:
self.instance.personalized = False
instance = super().save(*args, **kwargs)
instance.questionnaires.clear()
instance.questionnaires.add(*self.cleaned_data['questionnaires'])
try:
Questionnaire.check_constraints(self.event)
except ValidationError as exc:
raise ValidationError({'questionnaires': exc})
for questionnaire in self.cleaned_data['questionnaires']:
questionnaire.log_action('pretix.event.questionnaire.changed', user=self.user,
data={'item_added': self.instance.pk})
if not self.event.has_subevents and not self.cleaned_data.get('has_variations'):
if self.cleaned_data.get('quota_option') == self.EXISTING and self.cleaned_data.get('quota_add_existing') is not None:
quota = self.cleaned_data.get('quota_add_existing')
@@ -586,6 +625,11 @@ class ItemCreateForm(I18nModelForm):
)
if self.cleaned_data.get('copy_from'):
for question in self.cleaned_data['copy_from'].questions.all():
question.items.add(instance)
question.log_action('pretix.event.question.changed', user=self.user, data={
'item_added': self.instance.pk
})
for a in self.cleaned_data['copy_from'].addons.all():
instance.addons.create(addon_category=a.addon_category, min_count=a.min_count, max_count=a.max_count,
price_included=a.price_included, position=a.position,
@@ -625,6 +669,7 @@ class ItemCreateForm(I18nModelForm):
'internal_name',
'category',
'admission',
'personalized',
'default_price',
'tax_rule',
]
@@ -657,14 +702,6 @@ class ItemUpdateForm(I18nModelForm):
max_size=settings.FILE_UPLOAD_MAX_SIZE_IMAGE,
required=False,
)
questionnaires = SafeModelMultipleChoiceField(
queryset=Questionnaire.objects.none(),
required=False,
label=_('Questionnaires'),
widget=forms.CheckboxSelectMultiple(attrs={
'class': 'scrolling-multiple-choice'
}),
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@@ -760,9 +797,6 @@ class ItemUpdateForm(I18nModelForm):
)
self.fields['category'].widget.choices = self.fields['category'].choices
self.fields['questionnaires'].queryset = self.instance.event.questionnaires.filter(type__startswith='position_')
self.initial['questionnaires'] = self.instance.questionnaires.values_list('pk', flat=True)
self.fields['free_price_suggestion'].widget.attrs['data-display-dependency'] = '#id_free_price'
self.fields['validity_dynamic_start_choice'] = forms.TypedChoiceField(
@@ -826,8 +860,11 @@ class ItemUpdateForm(I18nModelForm):
)
)
if not d.get('admission'):
d['personalized'] = False
if d.get('grant_membership_type'):
if not d['grant_membership_type'].transferable and not d['personalized']: # TODO(questionnaires)
if not d['grant_membership_type'].transferable and not d['personalized']:
self.add_error(
'personalized' if d.get('admission') else 'admission',
_("Your product grants a non-transferable membership and should therefore be a personalized "
@@ -854,16 +891,6 @@ class ItemUpdateForm(I18nModelForm):
return d
def save(self, *args, **kwargs):
instance = super().save(*args, **kwargs)
instance.questionnaires.clear()
instance.questionnaires.add(*self.cleaned_data['questionnaires'])
try:
Questionnaire.check_constraints(self.event)
except ValidationError as exc:
raise ValidationError({'questionnaires': exc})
return instance
class Meta:
model = Item
localized_fields = '__all__'
@@ -875,6 +902,7 @@ class ItemUpdateForm(I18nModelForm):
'all_sales_channels',
'limit_sales_channels',
'admission',
'personalized',
'description',
'picture',
'default_price',
@@ -1169,10 +1197,6 @@ class ItemAddOnForm(I18nModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['addon_category'].queryset = self.event.categories.all()
self.fields['addon_category'].help_text = format_html('<a href="{}" data-iframe-dialog="true" data-iframe-dialog-target="<[name$=addon_category]" target="_blank">{}</a>', reverse('control:event.items.categories.add', kwargs={
'event': self.event.slug,
'organizer': self.event.organizer.slug,
}), _("Create a new category"))
self.fields['addon_category'].widget = Select2(
attrs={
'data-model-select2': 'generic',
+1 -1
View File
@@ -66,7 +66,7 @@ class ProcessForm(forms.Form):
widget=forms.Select(
attrs={'data-static': 'true'}
),
help_text=conditional_escape(c.help_text),
help_text=conditional_escape(c.help_text or ""),
)
def get_columns(self):
+2 -2
View File
@@ -364,7 +364,7 @@ class TeamForm(forms.ModelForm):
for opt in pg.options
],
label=pg.label,
help_text=conditional_escape(pg.help_text),
help_text=conditional_escape(pg.help_text or ""),
initial=initial,
widget=forms.RadioSelect,
)
@@ -389,7 +389,7 @@ class TeamForm(forms.ModelForm):
for opt in pg.options
],
label=pg.label,
help_text=conditional_escape(pg.help_text),
help_text=conditional_escape(pg.help_text or ""),
initial=initial,
widget=forms.RadioSelect,
)
-3
View File
@@ -866,9 +866,6 @@ class OrganizerPluginStateLogEntryType(LogEntryType):
'pretix.event.question.option.added': _('An answer option has been added to the question.'),
'pretix.event.question.option.deleted': _('An answer option has been removed from the question.'),
'pretix.event.question.option.changed': _('An answer option has been changed.'),
'pretix.event.questionnaire.added': _('A questionnaire has been created.'),
'pretix.event.questionnaire.deleted': _('A questionnaire has been deleted.'),
'pretix.event.questionnaire.changed': _('A questionnaire has been changed.'),
'pretix.event.permissions.added': _('A user has been added to the event team.'),
'pretix.event.permissions.invited': _('A user has been invited to the event team.'),
'pretix.event.permissions.changed': _('A user\'s permissions have been changed.'),
+3 -3
View File
@@ -182,12 +182,12 @@ def get_event_navigation(request: HttpRequest):
'active': 'event.items.categories' in url.url_name,
},
{
'label': _('Questionnaires'),
'url': reverse('control:event.items.questionnaires', kwargs={
'label': _('Questions'),
'url': reverse('control:event.items.questions', kwargs={
'event': request.event.slug,
'organizer': request.event.organizer.slug,
}),
'active': 'event.items.questionnaires' in url.url_name or 'event.items.questions' in url.url_name,
'active': 'event.items.questions' in url.url_name,
},
{
'label': _('Discounts'),
@@ -76,7 +76,7 @@
{% for q in result.questions %}
<li>
<a href="{% url "control:event.items.questions.show" organizer=request.event.organizer.slug event=request.event.slug question=q.id %}">
{{ q.internal_name }}
{{ q.question }}
</a>
</li>
{% endfor %}
@@ -115,7 +115,7 @@
{% if a.question.show_during_checkin %}
<p>
<span class="fa fa-question-circle text-muted fa-fw"></span>
<strong>{{ a.question.internal_name }}</strong>
<strong>{{ a.question.question }}</strong>
{{ a }}
</p>
{% endif %}
@@ -4,7 +4,6 @@
{% load static %}
{% load hierarkey_form %}
{% load formset_tags %}
{% load icon %}
{% block title %}{% trans "General settings" %}{% endblock %}
{% block custom_header %}
{{ block.super }}
@@ -95,6 +94,13 @@
</div>
</div>
<h4>{% trans "Attendee data (once per personalized ticket)" %}</h4>
{% bootstrap_field sform.attendee_names_asked_required layout="control" %}
{% bootstrap_field sform.attendee_emails_asked_required layout="control" %}
{% bootstrap_field sform.attendee_company_asked_required layout="control" %}
{% bootstrap_field sform.attendee_addresses_asked_required layout="control" %}
<div class="form-group">
<label class="control-label col-md-3">
{% trans "Custom fields" %}
@@ -103,30 +109,12 @@
<p>
<a href="{% url "control:event.items.questions" event=request.event.slug organizer=request.organizer.slug %}"
target="_blank">
{% trans "Manage questionnaires" %}
</a>
</p>
</div>
</div>
<h4>{% trans "Attendee data (once per personalized ticket)" %}</h4>
<div class="form-group">
<label class="control-label col-md-3">
</label>
<div class="col-md-9 static-form-row">
<p>
<a href="{% url "control:event.items.questionnaires" event=request.event.slug organizer=request.organizer.slug %}"
target="_blank" class="btn btn-default">
{% icon "wrench" %} {% trans "Manage questionnaires" %}
</a>
<a href="{% url "control:event.items.questions" event=request.event.slug organizer=request.organizer.slug %}"
target="_blank" class="btn btn-default">
{% icon "wrench" %} {% trans "Manage data fields" %}
{% trans "Manage questions" %}
</a>
</p>
</div>
</div>
{% bootstrap_field sform.attendee_data_explanation_text layout="control" %}
<h4>{% trans "Form settings" %}</h4>
{% bootstrap_field sform.name_scheme layout="control" %}
@@ -64,7 +64,47 @@
</div>
</div>
{% bootstrap_field form.questionnaires layout="control" %}
<div class="form-group" data-display-dependency="#admission_on">
<label class="col-md-3 control-label">{% trans "Personalization" %}</label>
<div class="col-md-9">
<div class="big-radio radio">
<label>
<input type="radio" value="on" name="{{ form.personalized.html_name }}" {% if form.personalized.value %}checked{% endif %}>
<span class="fa fa-fw fa-id-card-o"></span>
<strong>{% trans "Personalized ticket" %}</strong><br>
<div class="help-block">
{% blocktrans trimmed %}
When this ticket is purchased, the system will ask for a name or other details according
to your event settings.
{% endblocktrans %}
{% if not request.event.settings.attendee_names_asked and not request.event.settings.attendee_emails_asked and not request.event.settings.attendee_company_asked and not request.event.settings.attendee_addresses_asked %}
<br>
<span class="text-warning">
<span class="fa fa-warning" aria-hidden="true"></span>
{% trans "This will currently have no effect since all data fields are turned off in event settings." %}
</span>
<a href="{% url "control:event.settings" organizer=request.event.organizer.slug event=request.event.slug %}#tab-0-2-open"
class="btn btn-default btn-xs" target="_blank">{% trans "Change settings" %}</a>
{% endif %}
</div>
</label>
</div>
<div class="big-radio radio">
<label>
<input type="radio" value="" name="{{ form.personalized.html_name }}" {% if not form.personalized.value %}checked{% endif %}>
<span class="fa fa-fw fa-circle-o"></span>
<strong>{% trans "Non-personalized ticket" %}</strong>
<div class="help-block">
{% blocktrans trimmed %}
The system will not ask for a name or other attendee details. This only affects
system-provided fields, you can still add your own questions.
{% endblocktrans %}
</div>
</label>
</div>
</div>
</div>
{% bootstrap_field form.category layout="control" %}
<div class="form-group">
@@ -72,7 +72,51 @@
</div>
</div>
{% bootstrap_field form.questionnaires layout="control" %}
<div class="form-group" data-display-dependency="#admission_on">
<label class="col-md-3 control-label">{% trans "Personalization" %}</label>
<div class="col-md-9">
{% for e in form.errors.personalized %}
<div class="alert alert-danger has-error">
{{ e }}
</div>
{% endfor %}
<div class="big-radio radio">
<label>
<input type="radio" value="on" name="{{ form.personalized.html_name }}" {% if form.personalized.value %}checked{% endif %}>
<span class="fa fa-fw fa-id-card-o"></span>
<strong>{% trans "Personalized ticket" %}</strong><br>
<div class="help-block">
{% blocktrans trimmed %}
When this ticket is purchased, the system will ask for a name or other details according
to your event settings.
{% endblocktrans %}
{% if not request.event.settings.attendee_names_asked and not request.event.settings.attendee_emails_asked and not request.event.settings.attendee_company_asked and not request.event.settings.attendee_addresses_asked %}
<br>
<span class="text-warning">
<span class="fa fa-warning" aria-hidden="true"></span>
{% trans "This will currently have no effect since all data fields are turned off in event settings." %}
</span>
<a href="{% url "control:event.settings" organizer=request.event.organizer.slug event=request.event.slug %}#tab-0-2-open"
class="btn btn-default btn-xs" target="_blank">{% trans "Change settings" %}</a>
{% endif %}
</div>
</label>
</div>
<div class="big-radio radio">
<label>
<input type="radio" value="" name="{{ form.personalized.html_name }}" {% if not form.personalized.value %}checked{% endif %}>
<span class="fa fa-fw fa-file-text-o"></span>
<strong>{% trans "Non-personalized ticket" %}</strong>
<div class="help-block">
{% blocktrans trimmed %}
The system will not ask for a name or other attendee details. This only affects
system-provided fields, you can still add your own questions.
{% endblocktrans %}
</div>
</label>
</div>
</div>
</div>
{% bootstrap_field form.description layout="control" %}
{% bootstrap_field form.picture layout="control" %}
@@ -45,7 +45,6 @@
<th class="iconcol"></th>
<th class="iconcol"></th>
<th class="iconcol"></th>
<th class="iconcol"></th>
<th class="text-right flip">{% trans "Default price" %}</th>
<th class="action-col-2"><span class="sr-only">Edit</span></th>
</tr>
@@ -109,25 +108,15 @@
</td>
<td>
{% if i.admission %}
<span class="fa fa-user fa-fw text-muted" data-toggle="tooltip" title="{% trans "Admission ticket" %}"></span>
{% if i.personalized %}
<span class="fa fa-id-card-o fa-fw text-muted" data-toggle="tooltip" title="{% trans "Personalized admission ticket" %}"></span>
{% else %}
<span class="fa fa-user fa-fw text-muted" data-toggle="tooltip" title="{% trans "Admission ticket without personalization" %}"></span>
{% endif %}
{% elif i.issue_giftcard %}
<span class="fa fa-gift fa-fw text-muted" data-toggle="tooltip" title="{% trans "Gift card" %}"></span>
{% endif %}
</td>
<td>
{% if i.attendee_data_required %}
<i class="fa-stack fa-stack-small fa-fw " data-toggle="tooltip_html" title="<div class='text-left'>{% trans "Personal data of attendees required" %}. {% if i.custom_questions_asked %}{% trans "Custom questions asked" %}. {% endif %}{% trans "Questionnaires" %}:<br>{{ i.questionnaire_names_html }}</div>">
<i class="fa text-muted fa-id-card-o fa-stack-1x"></i>
<i class="fa fa-stack-shifted fa-asterisk fa-stack-1x fa-stack-shift-up fa-stack-sm"></i>
</i>
{% elif i.attendee_data_asked %}
<i class="fa-stack fa-stack-small fa-fw" data-toggle="tooltip_html" title="<div class='text-left'>{% trans "Personal data of attendees asked" %}. {% if i.custom_questions_asked %}{% trans "Custom questions asked" %}. {% endif %}{% trans "Questionnaires" %}:<br>{{ i.questionnaire_names_html }}</div>">
<span class="fa fa-id-card-o fa-fw text-muted" ></span>
</i>
{% elif i.custom_questions_asked %}
<span class="fa fa-question-circle-o fa-fw text-muted" data-toggle="tooltip_html" title="<div class='text-left'>{% trans "Custom questions asked" %}. {% trans "Questionnaires" %}:<br>{{ i.questionnaire_names_html }}</div>"></span>
{% endif %}
</td>
<td>
{% if i.var_count %}
<span class="fa fa-bars fa-fw text-muted" data-toggle="tooltip" title="{% trans "Product with variations" %}"></span>
@@ -3,10 +3,10 @@
{% load bootstrap3 %}
{% load escapejson %}
{% load formset_tags %}
{% block title %}{% blocktrans with name=question.internal_name %}Data field: {{ name }}{% endblocktrans %}{% endblock %}
{% block title %}{% blocktrans with name=question.question %}Question: {{ name }}{% endblocktrans %}{% endblock %}
{% block inside %}
<h1>
{% blocktrans with name=question.internal_name %}Data field: {{ name }}{% endblocktrans %}
{% blocktrans with name=question.question %}Question: {{ name }}{% endblocktrans %}
{% if 'event.items:write' in request.eventpermset %}
<a href="{% url "control:event.items.questions.edit" event=request.event.slug organizer=request.event.organizer.slug question=question.pk %}"
class="btn btn-default">
@@ -1,16 +1,16 @@
{% extends "pretixcontrol/items/base.html" %}
{% load i18n %}
{% load bootstrap3 %}
{% block title %}{% trans "Delete data field" %}{% endblock %}
{% block title %}{% trans "Delete question" %}{% endblock %}
{% block inside %}
<h1>{% trans "Delete data field" %}</h1>
<h1>{% trans "Delete question" %}</h1>
<form action="" method="post" class="form-horizontal">
{% csrf_token %}
<p>{% blocktrans %}Are you sure you want to delete the data field <strong>{{ question }}</strong>?{% endblocktrans %}</p>
<p>{% blocktrans %}Are you sure you want to delete the question <strong>{{ question }}</strong>?{% endblocktrans %}</p>
{% if dependent|length > 0 %}
<div class="alert alert-warning">
<p>{% blocktrans %}All answers to the question given by the buyers of the following products will be <strong>lost</strong>.{% endblocktrans %}
{% blocktrans with url=edit_url|add:"#tab-0-1-open" %}If you want to keep the answers, <a href="{{url}}">edit the data field</a> and set it to hidden.{% endblocktrans %}
{% blocktrans with url=edit_url|add:"#tab-0-1-open" %}If you want to keep the answers, <a href="{{url}}">edit the question</a> and set it to hidden.{% endblocktrans %}
</p>
</div>
<ul>
@@ -24,7 +24,7 @@
{% trans "Cancel" %}
</a>
<button type="submit" class="btn btn-danger btn-save">
{% trans "Delete data field and all answers" %}
{% trans "Delete question and all answers" %}
</button>
</div>
</form>
@@ -5,143 +5,158 @@
{% load escapejson %}
{% block title %}
{% if question %}
{% blocktrans with name=question.internal_name %}Data field: {{ name }}{% endblocktrans %}
{% blocktrans with name=question.question %}Question: {{ name }}{% endblocktrans %}
{% else %}
{% trans "Create new data field" %}
{% trans "Question" %}
{% endif %}
{% endblock %}
{% block inside %}
{% if question %}
<h1>{% blocktrans with name=question.internal_name %}Data field: {{ name }}{% endblocktrans %}</h1>
<h1>{% blocktrans with name=question.question %}Question: {{ name }}{% endblocktrans %}</h1>
{% else %}
<h1>{% trans "Create new data field" %}</h1>
<h1>{% trans "Question" %}</h1>
{% endif %}
<form action="" method="post" class="form-horizontal">
{% csrf_token %}
{% bootstrap_form_errors form %}
{% bootstrap_field form.internal_name layout="control" %}
{% bootstrap_field form.type layout="control" %}
<div id="valid-number" class="panel panel-default">
<div class="panel-heading"><h4 class="panel-title">{% trans "Validation" %}</h4></div>
<div class="panel-body">
{% bootstrap_field form.valid_number_min layout="control" %}
{% bootstrap_field form.valid_number_max layout="control" %}
</div>
</div>
<div id="valid-date" class="panel panel-default">
<div class="panel-heading"><h4 class="panel-title">{% trans "Validation" %}</h4></div>
<div class="panel-body">
{% bootstrap_field form.valid_date_min layout="control" %}
{% bootstrap_field form.valid_date_max layout="control" %}
</div>
</div>
<div id="valid-datetime" class="panel panel-default">
<div class="panel-heading"><h4 class="panel-title">{% trans "Validation" %}</h4></div>
<div class="panel-body">
{% bootstrap_field form.valid_datetime_min layout="control" %}
{% bootstrap_field form.valid_datetime_max layout="control" %}
</div>
</div>
<div id="valid-string" class="panel panel-default">
<div class="panel-heading"><h4 class="panel-title">{% trans "Validation" %}</h4></div>
<div class="panel-body">
{% bootstrap_field form.valid_string_length_min layout="control" %}
{% bootstrap_field form.valid_string_length_max layout="control" %}
</div>
</div>
<div id="valid-file" class="panel panel-default">
<div class="panel-heading"><h4 class="panel-title">{% trans "Validation" %}</h4></div>
<div class="panel-body">
{% bootstrap_field form.valid_file_portrait layout="control" %}
</div>
</div>
<div id="answer-options" class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">{% trans "Answer options" %}</h4>
</div>
<div class="panel-body">
<noscript>
<p>{% trans "Only applicable if you choose 'Choose one/multiple from a list' above." %}</p>
</noscript>
<div class="formset" data-formset data-formset-prefix="{{ formset.prefix }}" data-formset-delete-confirm-text="{% trans "If you delete an answer option, you will no longer be able to see statistical data on customers who previously selected this option, and when such customers edit their answers, they need to select a different option." %}">
{{ formset.management_form }}
{% bootstrap_formset_errors formset %}
<div data-formset-body>
{% for form in formset %}
<div data-formset-form>
<div class="sr-only">
{{ form.id }}
{% bootstrap_field form.DELETE form_group_class="" layout="inline" %}
{% bootstrap_field form.ORDER form_group_class="" layout="inline" %}
</div>
<div class="row question-option-row">
<div class="col-xs-10">
<span class="text-muted">
{% blocktrans trimmed with id=form.instance.identifier %}
Answer option {{ id }}
{% endblocktrans %}
</span>
{% bootstrap_form_errors form %}
{% bootstrap_field form.answer layout='inline' form_group_class="" %}
</div>
<div class="col-xs-2 text-right flip">
<span>&nbsp;</span><br>
<button type="button" class="btn btn-default" data-formset-move-up-button>
<i class="fa fa-arrow-up"></i></button>
<button type="button" class="btn btn-default" data-formset-move-down-button>
<i class="fa fa-arrow-down"></i></button>
<button type="button" class="btn btn-danger" data-formset-delete-button>
<i class="fa fa-trash"></i></button>
</div>
</div>
</div>
{% endfor %}
</div>
<script type="form-template" data-formset-empty-form>
{% escapescript %}
<div data-formset-form>
<div class="sr-only">
{{ formset.empty_form.id }}
{% bootstrap_field formset.empty_form.DELETE form_group_class="" layout="inline" %}
{% bootstrap_field formset.empty_form.ORDER form_group_class="" layout="inline" %}
</div>
<div class="row question-option-row">
<div class="col-xs-10">
<span class="text-muted">
{% trans "New answer option" %}
</span>
{% bootstrap_field formset.empty_form.answer layout='inline' form_group_class="" %}
</div>
<div class="col-xs-2 text-right flip">
<span>&nbsp;</span><br>
<button type="button" class="btn btn-default" data-formset-move-up-button>
<i class="fa fa-arrow-up"></i></button>
<button type="button" class="btn btn-default" data-formset-move-down-button>
<i class="fa fa-arrow-down"></i></button>
<button type="button" class="btn btn-danger" data-formset-delete-button>
<i class="fa fa-trash"></i></button>
</div>
</div>
</div>
{% endescapescript %}
</script>
<p>
<button type="button" class="btn btn-default" data-formset-add>
<i class="fa fa-plus"></i> {% trans "Add a new option" %}</button>
</p>
<div class="tabbed-form">
<fieldset>
<legend>{% trans "General" %}</legend>
{% bootstrap_field form.question layout="control" %}
{% bootstrap_field form.type layout="control" %}
{% if form.items %}
{% bootstrap_field form.items layout="control" %}
{% endif %}
{% bootstrap_field form.required layout="control" %}
<div class="alert alert-info alert-required-boolean">
{% blocktrans trimmed %}
If you mark a Yes/No question as required, it means that the user has to select Yes and No is not
accepted. If you want to allow both options, do not make this field required.
{% endblocktrans %}
</div>
</div>
<div id="valid-number">
{% bootstrap_field form.valid_number_min layout="control" %}
{% bootstrap_field form.valid_number_max layout="control" %}
</div>
<div id="valid-date">
{% bootstrap_field form.valid_date_min layout="control" %}
{% bootstrap_field form.valid_date_max layout="control" %}
</div>
<div id="valid-datetime">
{% bootstrap_field form.valid_datetime_min layout="control" %}
{% bootstrap_field form.valid_datetime_max layout="control" %}
</div>
<div id="valid-string">
{% bootstrap_field form.valid_string_length_min layout="control" %}
{% bootstrap_field form.valid_string_length_max layout="control" %}
</div>
<div id="valid-file">
{% bootstrap_field form.valid_file_portrait layout="control" %}
</div>
<div id="answer-options">
<h3>{% trans "Answer options" %}</h3>
<noscript>
<p>{% trans "Only applicable if you choose 'Choose one/multiple from a list' above." %}</p>
</noscript>
<div class="formset" data-formset data-formset-prefix="{{ formset.prefix }}" data-formset-delete-confirm-text="{% trans "If you delete an answer option, you will no longer be able to see statistical data on customers who previously selected this option, and when such customers edit their answers, they need to select a different option." %}">
{{ formset.management_form }}
{% bootstrap_formset_errors formset %}
<div data-formset-body>
{% for form in formset %}
<div data-formset-form>
<div class="sr-only">
{{ form.id }}
{% bootstrap_field form.DELETE form_group_class="" layout="inline" %}
{% bootstrap_field form.ORDER form_group_class="" layout="inline" %}
</div>
<div class="row question-option-row">
<div class="col-xs-10">
<span class="text-muted">
{% blocktrans trimmed with id=form.instance.identifier %}
Answer option {{ id }}
{% endblocktrans %}
</span>
{% bootstrap_form_errors form %}
{% bootstrap_field form.answer layout='inline' form_group_class="" %}
</div>
<div class="col-xs-2 text-right flip">
<span>&nbsp;</span><br>
<button type="button" class="btn btn-default" data-formset-move-up-button>
<i class="fa fa-arrow-up"></i></button>
<button type="button" class="btn btn-default" data-formset-move-down-button>
<i class="fa fa-arrow-down"></i></button>
<button type="button" class="btn btn-danger" data-formset-delete-button>
<i class="fa fa-trash"></i></button>
</div>
</div>
</div>
{% endfor %}
</div>
<script type="form-template" data-formset-empty-form>
{% escapescript %}
<div data-formset-form>
<div class="sr-only">
{{ formset.empty_form.id }}
{% bootstrap_field formset.empty_form.DELETE form_group_class="" layout="inline" %}
{% bootstrap_field formset.empty_form.ORDER form_group_class="" layout="inline" %}
</div>
<div class="row question-option-row">
<div class="col-xs-10">
<span class="text-muted">
{% trans "New answer option" %}
</span>
{% bootstrap_field formset.empty_form.answer layout='inline' form_group_class="" %}
</div>
<div class="col-xs-2 text-right flip">
<span>&nbsp;</span><br>
<button type="button" class="btn btn-default" data-formset-move-up-button>
<i class="fa fa-arrow-up"></i></button>
<button type="button" class="btn btn-default" data-formset-move-down-button>
<i class="fa fa-arrow-down"></i></button>
<button type="button" class="btn btn-danger" data-formset-delete-button>
<i class="fa fa-trash"></i></button>
</div>
</div>
</div>
{% endescapescript %}
</script>
<p>
<button type="button" class="btn btn-default" data-formset-add>
<i class="fa fa-plus"></i> {% trans "Add a new option" %}</button>
</p>
</div>
</div>
</fieldset>
<fieldset>
<legend>{% trans "Advanced" %}</legend>
{% bootstrap_field form.help_text layout="control" %}
{% bootstrap_field form.identifier layout="control" %}
{% if form.ask_during_checkin %}
{% bootstrap_field form.ask_during_checkin layout="control" %}
{% endif %}
{% if form.show_during_checkin %}
{% bootstrap_field form.show_during_checkin layout="control" %}
{% endif %}
{% bootstrap_field form.hidden layout="control" %}
{% if form.print_on_invoice %}
{% bootstrap_field form.print_on_invoice layout="control" %}
{% endif %}
<div class="form-group">
<label class="col-md-3 control-label" for="id_dependency_question">
{% trans "Question dependency" %}
<br><span class="optional">{% trans "Optional" context "form" %}</span>
</label>
<div class="col-md-4">
{% bootstrap_field form.dependency_question layout="inline" form_group_class="inner" %}
</div>
<div class="col-md-5">
<script type="text/plain" id="dependency_value_val">{{ form.instance.dependency_values|escapejson_dumps }}</script>
{% bootstrap_field form.dependency_values layout="inline" form_group_class="inner" %}
</div>
</div>
</fieldset>
</div>
{% bootstrap_field form.identifier layout="control" %}
{% if form.show_during_checkin %}
{% bootstrap_field form.show_during_checkin layout="control" %}
{% endif %}
{% if form.print_on_invoice %}
{% bootstrap_field form.print_on_invoice layout="control" %}
{% bootstrap_field form.print_on_invoice_label layout="control" %}
{% endif %}
<div class="form-group submit-group">
<button type="submit" class="btn btn-primary btn-save">
{% trans "Save" %}
@@ -1,65 +0,0 @@
{% extends "pretixcontrol/items/base.html" %}
{% load i18n %}
{% load bootstrap3 %}
{% load static %}
{% load icon %}
{% load compress %}
{% load vite %}
{% block title %}
{% trans "Questionnaires" %}
{% endblock %}
{% block inside %}
<h1>
{% trans "Questionnaires" %}
<a href="{% url "control:event.items.questions" organizer=request.event.organizer.slug event=request.event.slug %}" class="btn btn-default pull-right">
{% icon "wrench" %} {% trans "Manage data fields" %}
</a>
</h1>
<p>
{% blocktrans trimmed %}
Questionaires allow your attendees to fill in additional data about their ticket. If you provide food, one
example might be to ask your users about preferences or dietary requirements.
{% endblocktrans %}
</p>
<p>
{% blocktrans trimmed %}
Each questionnaire can be assigned to one or more products for which its questions are asked. It can appear
either during the checkout process, in the ticket details for each attendee individually, or at the check-in
at the venue.
{% endblocktrans %}
</p>
<p>
{% blocktrans trimmed %}
The answer to each question is stored either in a system-provided attendee data field (such as name, email,
or postal address), or in a user-defined data field attached to the order or the attendee.
{% endblocktrans %}
{% blocktrans trimmed %}
User-defined data fields can be created from the questionnaire editor below, and managed using the button to the right.
{% endblocktrans %}
</p>
<br>
{% csrf_token %}
{{ locales|json_script:"event_locales" }}
{{ questionnaire_type_choices|json_script:"questionnaire_type_choices" }}
{{ question_type_choices|json_script:"question_type_choices" }}
{{ system_question_choices|json_script:"system_question_choices" }}
{% url "control:event.items.questions.edit" organizer=request.event.organizer.slug event=request.event.slug question=0 as datafield_edit_url %}
{{ datafield_edit_url|json_script:"datafield_edit_url" }}
{% url "control:event.items.questions.show" organizer=request.event.organizer.slug event=request.event.slug question=0 as datafield_view_url %}
{{ datafield_view_url|json_script:"datafield_view_url" }}
{% url "control:event.items.questions.add" organizer=request.event.organizer.slug event=request.event.slug as datafield_create_url %}
{{ datafield_create_url|json_script:"datafield_create_url" }}
<div id="questionnaires-editor">
<!-- Vue app mount point -->
<center><div class="big-load-indicator"><i class="fa fa-cog big-rotating-icon"></i></div></center>
</div>
{% vite_hmr %}
{% vite_asset "src/pretix/static/pretixcontrol/js/ui/questionnaires/index.ts" %}
{% endblock %}
@@ -1,8 +1,8 @@
{% extends "pretixcontrol/items/base.html" %}
{% load i18n %}
{% block title %}{% trans "Data fields" %}{% endblock %}
{% block title %}{% trans "Questions" %}{% endblock %}
{% block inside %}
<h1>{% trans "Data fields" %}</h1>
<h1>{% trans "Questions" %}</h1>
<p>
{% blocktrans trimmed %}
Questions allow your attendees to fill in additional data about their ticket. If you provide food, one
@@ -11,52 +11,99 @@
</p>
{% csrf_token %}
{% if 'event.items:write' in request.eventpermset %}
<p>
<a href="{% url "control:event.items.questions.add" organizer=request.event.organizer.slug event=request.event.slug %}?container_type=O" class="btn btn-default"><i class="fa fa-plus"></i> {% trans "Create a new order-level data field" %}
</a>
<a href="{% url "control:event.items.questions.add" organizer=request.event.organizer.slug event=request.event.slug %}?container_type=P" class="btn btn-default"><i class="fa fa-plus"></i> {% trans "Create a new per-ticket data field" %}
</a>
</p>
{% endif %}
{% if request.event.settings.feature_flag_order_level_questions %}
{% if 'event.items:write' in request.eventpermset %}
<p>
<a href="{% url "control:event.items.questions.add" organizer=request.event.organizer.slug event=request.event.slug %}?container_type=P" class="btn btn-default"><i class="fa fa-plus"></i> {% trans "Create a new per-ticket question" %}
</a>
<a href="{% url "control:event.items.questions.add" organizer=request.event.organizer.slug event=request.event.slug %}?container_type=O" class="btn btn-default"><i class="fa fa-plus"></i> {% trans "Create a new order-level question" %}
</a>
</p>
{% endif %}
<h2>{% trans "Per-order data fields" %}</h2>
<p>{% trans "These data fields can be used on orders." %}</p>
<h2>{% trans "Per-ticket questions" %}</h2>
<p>{% trans "These questions are asked for every ticket, so possibly multiple times in the same order." %}</p>
{% else %}
{% if 'event.items:write' in request.eventpermset %}
<p>
<a href="{% url "control:event.items.questions.add" organizer=request.event.organizer.slug event=request.event.slug %}?container_type=P" class="btn btn-default"><i class="fa fa-plus"></i> {% trans "Create a new question" %}
</a>
</p>
{% endif %}
{% endif %}
<div class="table-responsive">
<table class="table table-hover table-quotas">
<thead>
<tr>
<th>{% trans "Internal name" %}</th>
<th>{% trans "Question" %}</th>
<th>{% trans "Type" %}</th>
<th class="iconcol"></th>
<th class="iconcol"></th>
<th class="iconcol"></th>
<th>{% trans "Products" %}</th>
{% if 'event.items:write' in request.eventpermset %}
<th class="action-col-2"></th>
{% endif %}
<th class="action-col-2"></th>
</tr>
</thead>
<tbody>
{% for q in questions %}{% if q.container_type == "O" %}
<tr>
<tbody data-dnd-url="{% url "control:event.items.questions.reorder" organizer=request.event.organizer.slug event=request.event.slug %}?container_type=P">
{% for q in questions %}{% if q.container_type == "P" %}
<tr data-dnd-id="{{ q.id }}">
<td>
<strong>
{{ q.internal_name }}
{% if q.pk %}
<a href="{% url "control:event.items.questions.show" organizer=request.event.organizer.slug event=request.event.slug question=q.id %}">
{% endif %}
{{ q.question }}
{% if q.pk %}
</a>
{% endif %}
</strong><br>
<small class="text-muted">{{ q.identifier }}</small>
</td>
<td>
{{ q.get_type_display }}
</td>
<td>
{% if q.show_during_checkin %}
<span class="fa fa-exclamation-circle text-muted" data-toggle="tooltip" title="{% trans "Show during check-in" %}"></span>
{% if q.pk %}
{{ q.get_type_display }}
{% else %}
{% trans "System question" %}
{% endif %}
</td>
<td>
{% if q.print_on_invoice %}
<span class="fa fa-file-o text-muted" data-toggle="tooltip" title="{% trans "Print answer on invoices" %}"></span>
{% if q.required %}
<span class="fa fa-exclamation-circle text-muted" data-toggle="tooltip" title="{% trans "Required question" %}"></span>
{% endif %}
</td>
<td>
{% if q.pk and q.ask_during_checkin %}
<span class="fa fa-check-square text-muted" data-toggle="tooltip" title="{% trans "Ask during check-in" %}"></span>
{% endif %}
</td>
<td>
{% if q.pk and q.hidden %}
<span class="fa fa-eye-slash text-muted" data-toggle="tooltip" title="{% trans "Hidden question" %}"></span>
{% endif %}
</td>
<td>
{% if q.pk %}
<ul>
{% for item in q.items.all %}
<li>
<a href="{% url "control:event.item" organizer=request.event.organizer.slug event=request.event.slug item=item.id %}">{{ item }}</a>
</li>
{% endfor %}
</ul>
{% else %}
<small>{% trans "All personalized products" %}</small>
{% endif %}
</td>
{% if 'event.items:write' in request.eventpermset %}
<td class="dnd-container">
</td>
{% endif %}
<td class="text-right flip">
{% if q.pk %}
<a href="{% url "control:event.items.questions.show" organizer=request.event.organizer.slug event=request.event.slug question=q.id %}" class="btn btn-default btn-sm"><i class="fa fa-bar-chart"></i></a>
{% if 'event.items:write' in request.eventpermset %}
<a href="{% url "control:event.items.questions.edit" organizer=request.event.organizer.slug event=request.event.slug question=q.id %}" class="btn btn-default btn-sm"><i class="fa fa-edit"></i></a>
<a href="{% url "control:event.items.questions.delete" organizer=request.event.organizer.slug event=request.event.slug question=q.id %}" class="btn btn-danger btn-sm"><i class="fa fa-trash"></i></a>
@@ -74,55 +121,85 @@
</table>
</div>
<h2>{% trans "Per-ticket data fields" %}</h2>
<p>{% trans "These data field can be used on individual tickets." %}</p>
<div class="table-responsive">
<table class="table table-hover table-quotas">
<thead>
<tr>
<th>{% trans "Internal name" %}</th>
<th>{% trans "Type" %}</th>
<th class="iconcol"></th>
<th class="iconcol"></th>
<th class="action-col-2"></th>
</tr>
</thead>
<tbody>
{% for q in questions %}{% if q.container_type == "P" %}
{% if request.event.settings.feature_flag_order_level_questions %}
<h2>
{% trans "Per-order questions" %}
<small><span class="label label-info" title="
{% trans "This functionality is in active development and expected to change significantly over the coming months." %}
{% trans "Per-order questions are currently not supported and will not be displayed in pretixPOS." %}
" data-toggle="tooltip">
<span class="fa fa-flask" aria-hidden="true"></span>
{% trans "Experimental feature" %}
</span></small>
</h2>
<p>{% trans "These questions are asked once per order." %}</p>
<div class="table-responsive">
<table class="table table-hover table-quotas">
<thead>
<tr>
<td>
<strong>
<a href="{% url "control:event.items.questions.show" organizer=request.event.organizer.slug event=request.event.slug question=q.id %}">
{{ q.internal_name }}
</a>
</strong><br>
<small class="text-muted">{{ q.identifier }}</small>
</td>
<td>
{{ q.get_type_display }}
</td>
<td>
{% if q.show_during_checkin %}
<span class="fa fa-check-square text-muted" data-toggle="tooltip" title="{% trans "Show answer during check-in" %}"></span>
{% endif %}
</td>
<td>
{% if q.print_on_invoice %}
<span class="fa fa-file-o text-muted" data-toggle="tooltip" title="{% trans "Print answer on invoices" %}"></span>
{% endif %}
</td>
<td class="text-right flip">
<a href="{% url "control:event.items.questions.show" organizer=request.event.organizer.slug event=request.event.slug question=q.id %}" class="btn btn-default btn-sm"><i class="fa fa-bar-chart"></i></a>
{% if 'event.items:write' in request.eventpermset %}
<a href="{% url "control:event.items.questions.edit" organizer=request.event.organizer.slug event=request.event.slug question=q.id %}" class="btn btn-default btn-sm"><i class="fa fa-edit"></i></a>
<a href="{% url "control:event.items.questions.delete" organizer=request.event.organizer.slug event=request.event.slug question=q.id %}" class="btn btn-danger btn-sm"><i class="fa fa-trash"></i></a>
{% endif %}
</td>
<th>{% trans "Question" %}</th>
<th>{% trans "Type" %}</th>
<th class="iconcol"></th>
<th class="iconcol"></th>
<th class="iconcol"></th>
{% if 'event.items:write' in request.eventpermset %}
<th class="action-col-2"></th>
{% endif %}
<th class="action-col-2"></th>
</tr>
{% endif %}{% endfor %}
</tbody>
</table>
</div>
</thead>
<tbody data-dnd-url="{% url "control:event.items.questions.reorder" organizer=request.event.organizer.slug event=request.event.slug %}?container_type=O">
{% for q in questions %}{% if q.container_type == "O" %}
<tr data-dnd-id="{{ q.id }}">
<td>
<strong>
{{ q.question }}
</strong><br>
<small class="text-muted">{{ q.identifier }}</small>
</td>
<td>
{% if q.pk %}
{{ q.get_type_display }}
{% else %}
{% trans "System question" %}
{% endif %}
</td>
<td>
{% if q.required %}
<span class="fa fa-exclamation-circle text-muted" data-toggle="tooltip" title="{% trans "Required question" %}"></span>
{% endif %}
</td>
<td>
{% if q.pk and q.ask_during_checkin %}
<span class="fa fa-check-square text-muted" data-toggle="tooltip" title="{% trans "Ask during check-in" %}"></span>
{% endif %}
</td>
<td>
{% if q.pk and q.hidden %}
<span class="fa fa-eye-slash text-muted" data-toggle="tooltip" title="{% trans "Hidden question" %}"></span>
{% endif %}
</td>
{% if 'event.items:write' in request.eventpermset %}
<td class="dnd-container">
</td>
{% endif %}
<td class="text-right flip">
{% if q.pk %}
{% if 'event.items:write' in request.eventpermset %}
<a href="{% url "control:event.items.questions.edit" organizer=request.event.organizer.slug event=request.event.slug question=q.id %}" class="btn btn-default btn-sm"><i class="fa fa-edit"></i></a>
<a href="{% url "control:event.items.questions.delete" organizer=request.event.organizer.slug event=request.event.slug question=q.id %}" class="btn btn-danger btn-sm"><i class="fa fa-trash"></i></a>
{% endif %}
{% else %}
{% if 'event.settings.general:write' in request.eventpermset %}
<a href="{% url "control:event.settings" organizer=request.event.organizer.slug event=request.event.slug %}#tab-0-2-open"
class="btn btn-default btn-sm"><i class="fa fa-wrench"></i></a>
{% endif %}
{% endif %}
</td>
</tr>
{% endif %}{% endfor %}
</tbody>
</table>
</div>
{% endif %}
{% endblock %}
@@ -1,11 +0,0 @@
{% extends "error.html" %}
{% load i18n %}
{% load eventurl %}
{% load urlreplace %}
{% load static %}
{% block content %}
<h1>{% trans "Please wait..." %}</h1>
{{ notify_info|json_script:"notify_info" }}
<script type="text/javascript" src="{% static "pretixcontrol/js/notify_parent.js" %}"></script>
{% endblock %}
@@ -20,10 +20,8 @@
{% endif %}
{% elif question.type == "M" %}
{{ answer.to_string_i18n|rich_text_snippet }}
{% elif question.type %}
{{ answer.to_string_i18n|rich_text_snippet }}
{% else %}
{{ answer|linebreaksbr }}
{{ answer.to_string_i18n|linebreaksbr }}
{% endif %}
{% else %}
<em>{% trans "not answered" %}</em>
@@ -428,23 +428,12 @@
</dd>
{% endif %}
{% if order.rendered_questions or order.rendered_questions.leftovers %}
{% if order.answers.all %}
<hr>
{% endif %}
{% for q in order.rendered_questions %}
<dt>{{ q.label }}</dt>
<dd>{% include "pretixcontrol/order/fragment_question_answer.html" with request=request question=q answer=q.answer %}</dd>
{% endfor %}
{% for q in order.rendered_questions.leftovers %}
<dt class="text-muted">
{{ q.label }}
<span class="fa fa-question-circle text-muted"
data-toggle="tooltip"
title="{% trans "This data field is not asked for this product, but an answer exists anyway." %}"
></span>
</dt>
<dd class="text-muted">{% include "pretixcontrol/order/fragment_question_answer.html" with request=request question=ans.question answer=ans %}</dd>
<!-- add a edit or delete button? -->
{% for ans in order.answers.all %}
<dt>{{ ans.question.internal_name|default:ans.question.question }}</dt>
<dd>{% include "pretixcontrol/order/fragment_question_answer.html" with request=request question=ans.question answer=ans %}</dd>
{% endfor %}
</dl>
</div>
@@ -621,44 +610,17 @@
{% endif %}
{% if line.has_questions %}
<dl>
{% for q in line.rendered_questions %}
{% if q.system_datafield == "@street" and line.rendered_questions.full_address_asked %}
<dt>
{% trans "Attendee address" %}
</dt>
<dd>
{% if line.street or line.zipcode or line.city or line.country %}
{{ line.street|default_if_none:""|linebreaksbr }}<br>
{{ line.zipcode|default_if_none:"" }} {{ line.city|default_if_none:"" }}<br>
{% if line.state %}{{ line.state_for_address }}<br>{% endif %}
{{ line.country.name|default_if_none:"" }}
{% else %}
<em>{% trans "not answered" %}</em>
{% endif %}
</dd>
{% elif q.system_datafield == "@zipcode" and line.rendered_questions.full_address_asked %}
{% elif q.system_datafield == "@city" and line.rendered_questions.full_address_asked %}
{% elif q.system_datafield == "@state" and line.rendered_questions.full_address_asked %}
{% elif q.system_datafield == "@country" and line.rendered_questions.full_address_asked %}
{% else %}
<dt>
{{ q.label }}
{% if q.questionnaire.ask_during_checkin %}
<span class="fa fa-qrcode text-muted"
data-toggle="tooltip"
title="{% trans "This question will be asked during check-in." %}"
></span>
{% endif %}
{% if q.questionnaire.hidden %}
<span class="fa fa-eye-slash text-muted"
data-toggle="tooltip"
title="{% trans "Hidden question" %}"
></span>
{% endif %}
</dt>
<dd>
{% include "pretixcontrol/order/fragment_question_answer.html" with request=request question=q answer=q.answer %}
{% if q.system_datafield == "@attendee_email" and not line.addon_to %}
{% if line.item.ask_attendee_data and event.settings.attendee_names_asked %}
<dt>{% trans "Attendee name" %}</dt>
<dd>{% if line.attendee_name %}{{ line.attendee_name_all_components }}{% else %}
<em>{% trans "not answered" %}</em>{% endif %}</dd>
{% endif %}
{% if line.item.ask_attendee_data and event.settings.attendee_emails_asked %}
<dt>{% trans "Attendee email" %}</dt>
<dd>
{% if line.attendee_email %}
{{ line.attendee_email }}
{% if not line.addon_to %}
<form class="form-inline helper-display-inline" method="post"
action="{% url "control:event.order.resendlink" event=request.event.slug organizer=request.event.organizer.slug code=order.code position=line.pk %}">
{% csrf_token %}
@@ -671,22 +633,50 @@
</button>
</form>
{% endif %}
</dd>
{% endif %}
{% endfor %}
{% for q in line.rendered_questions.leftovers %}
<dt class="text-muted">
{{ q.label }}
<span class="fa fa-question-circle text-muted"
data-toggle="tooltip"
title="{% trans "This data field is not asked for this product, but an answer exists anyway." %}"
></span>
{% else %}
<em>{% trans "not answered" %}</em>
{% endif %}
</dd>
{% endif %}
{% if line.item.ask_attendee_data and event.settings.attendee_company_asked %}
<dt>
{% trans "Attendee company" %}
</dt>
<dd class="text-muted">{% include "pretixcontrol/order/fragment_question_answer.html" with request=request question=q answer=q.answer %}</dd>
<!-- add a edit or delete button? -->
<dd>
{% if line.company %}{{ line.company }}{% else %}<em>{% trans "not answered" %}</em>{% endif %}
</dd>
{% endif %}
{% if line.item.ask_attendee_data and event.settings.attendee_addresses_asked %}
<dt>
{% trans "Attendee address" %}
</dt>
<dd>
{% if line.street or line.zipcode or line.city or line.country %}
{{ line.street|default_if_none:""|linebreaksbr }}<br>
{{ line.zipcode|default_if_none:"" }} {{ line.city|default_if_none:"" }}<br>
{% if line.state %}{{ line.state_for_address }}<br>{% endif %}
{{ line.country.name|default_if_none:"" }}
{% else %}
<em>{% trans "not answered" %}</em>
{% endif %}
</dd>
{% endif %}
{% for q in line.questions %}
<dt>
{{ q.question }}
{% if q.ask_during_checkin %}
<span class="fa fa-qrcode text-muted"
data-toggle="tooltip"
title="{% trans "This question will be asked during check-in." %}"
></span>
{% endif %}
</dt>
<dd>
{% include "pretixcontrol/order/fragment_question_answer.html" with request=request question=q answer=q.answer %}
</dd>
{% endfor %}
{% for q in line.additional_fields %}
<dt>{{ q.internal_name }}</dt>
<dt>{{ q.question }}</dt>
<dd>{% if q.answer %}{{ q.answer|linebreaksbr }}{% else %}
<em>{% trans "not answered" %}</em>{% endif %}</dd>
{% endfor %}
@@ -99,7 +99,7 @@
{% if filter_form.is_valid and filter_form.cleaned_data.question %}
<p class="text-muted">
<span class="fa fa-filter"></span>
{% blocktrans trimmed with question=filter_form.cleaned_data.question.internal_name %}
{% blocktrans trimmed with question=filter_form.cleaned_data.question.question %}
List filtered by answers to question "{{ question }}".
{% endblocktrans %}
<a href="?{% url_replace request 'question' '' 'answer' '' %}" class="text-muted">
+1 -1
View File
@@ -343,6 +343,7 @@ urlpatterns = [
name='event.items.categories.edit'),
re_path(r'^categories/add$', item.CategoryCreate.as_view(), name='event.items.categories.add'),
re_path(r'^questions/$', item.QuestionList.as_view(), name='event.items.questions'),
re_path(r'^questions/reorder$', item.reorder_questions, name='event.items.questions.reorder'),
re_path(r'^questions/(?P<question>\d+)/delete$', item.QuestionDelete.as_view(),
name='event.items.questions.delete'),
re_path(r'^questions/(?P<question>\d+)/$', item.QuestionView.as_view(),
@@ -350,7 +351,6 @@ urlpatterns = [
re_path(r'^questions/(?P<question>\d+)/change$', item.QuestionUpdate.as_view(),
name='event.items.questions.edit'),
re_path(r'^questions/add$', item.QuestionCreate.as_view(), name='event.items.questions.add'),
re_path(r'^questionnaires/$', item.QuestionnairesEditor.as_view(), name='event.items.questionnaires'),
re_path(r'^quotas/$', item.QuotaList.as_view(), name='event.items.quotas'),
re_path(r'^quotas/bulk_action$', item.QuotaBulkAction.as_view(), name='event.items.quotas.bulkaction'),
re_path(r'^quotas/bulk_edit$', item.QuotaBulkUpdateView.as_view(), name='event.items.quotas.bulkedit'),
-23
View File
@@ -22,12 +22,9 @@
import collections.abc
import warnings
from django.contrib import messages
from django.core.paginator import (
EmptyPage, PageNotAnInteger, UnorderedObjectListWarning,
)
from django.http.response import HttpResponseRedirect
from django.shortcuts import render
from django.utils.translation import gettext_lazy as _
from django.views.generic import edit
@@ -206,23 +203,3 @@ class LargeResultSetPaginator(object):
UnorderedObjectListWarning,
stacklevel=3
)
class TellParentFormMixin:
def dispatch(self, request, *args, **kwargs):
response = super().dispatch(request, *args, **kwargs)
if response.get("X-Frame-Options") is None:
response["X-Frame-Options"] = "SAMEORIGIN"
return response
def form_valid(self, form):
result = super().form_valid(form)
if self.request.GET.get('notify_parent') and isinstance(result, HttpResponseRedirect):
message_store = messages.get_messages(self.request)
msgs = [{'level': msg.level_tag, 'message': msg.message} for msg in message_store]
return render(self.request, 'pretixcontrol/notify_parent.html', {
'notify_info': {'object': self.object.pk, 'object_str': str(self.object), 'redirect_url': result.url, 'messages': msgs},
})
else:
return result
+3 -7
View File
@@ -105,7 +105,7 @@ from pretix.presale.views.widget import (
from ...base.i18n import language
from ...base.models.items import (
Item, ItemCategory, ItemMetaProperty, Question, Questionnaire, QuestionnaireRow, Quota,
Item, ItemCategory, ItemMetaProperty, Question, Quota,
)
from ...base.permissions import AnyPermissionOf
from ...base.plugins import (
@@ -1652,6 +1652,7 @@ class QuickSetupView(EventPermissionRequiredMixin, FormView):
self.request.event.settings.show_quota_left = form.cleaned_data['show_quota_left']
self.request.event.settings.waiting_list_enabled = form.cleaned_data['waiting_list_enabled']
self.request.event.settings.attendee_names_required = form.cleaned_data['attendee_names_required']
self.request.event.settings.contact_mail = form.cleaned_data['contact_mail']
self.request.event.settings.imprint_url = form.cleaned_data['imprint_url']
self.request.event.log_action('pretix.event.settings', user=self.request.user, data={
@@ -1668,11 +1669,6 @@ class QuickSetupView(EventPermissionRequiredMixin, FormView):
category.log_action('pretix.event.category.added', data={'name': gettext('Tickets')},
user=self.request.user)
questionnaire = self.request.event.get_default_questionnaire()
questionnaire.rows.filter(system_datafield=QuestionnaireRow.SystemDatafield.ATTENDEE_NAME_PARTS).update(
required=form.cleaned_data['attendee_names_required']
)
subevent = self.request.event.subevents.first()
for i, f in enumerate(self.formset):
if f in self.formset.deleted_forms or not f.has_changed():
@@ -1685,10 +1681,10 @@ class QuickSetupView(EventPermissionRequiredMixin, FormView):
default_price=f.cleaned_data['default_price'] or 0,
tax_rule=tax_rule,
admission=True,
personalized=True,
position=i,
all_sales_channels=True,
)
item.questionnaires.add(questionnaire)
item.log_action('pretix.event.item.added', user=self.request.user, data=dict(f.cleaned_data))
if f.cleaned_data['quota'] or not form.cleaned_data['total_quota']:
quota = self.request.event.quotas.create(
+86 -75
View File
@@ -38,9 +38,8 @@ from collections import OrderedDict, namedtuple
from itertools import groupby
from json.decoder import JSONDecodeError
from django.conf import settings
from django.contrib import messages
from django.core.exceptions import PermissionDenied, ValidationError
from django.core.exceptions import PermissionDenied
from django.core.files import File
from django.db import models, transaction
from django.db.models import (
@@ -54,12 +53,10 @@ from django.http import (
from django.shortcuts import redirect, render
from django.urls import resolve, reverse
from django.utils.functional import cached_property
from django.utils.html import format_html_join
from django.utils.safestring import mark_safe
from django.utils.timezone import now
from django.utils.translation import gettext, gettext_lazy as _
from django.views.decorators.http import require_http_methods
from django.views.generic import FormView, ListView, TemplateView, View
from django.views.generic import FormView, ListView, View
from django.views.generic.detail import DetailView, SingleObjectMixin
from django_countries.fields import Country
@@ -68,15 +65,14 @@ from pretix.api.serializers.item import (
ItemVariationSerializer,
)
from pretix.base.forms import I18nFormSet
from pretix.base.forms.questions import get_fake_attendee_questions
from pretix.base.models import (
CartPosition, Item, ItemCategory, ItemProgramTime, ItemVariation, LogEntry,
OrderPosition, Question, QuestionAnswer, QuestionnaireRow, QuestionOption,
Quota, SeatCategoryMapping, Voucher,
OrderPosition, Question, QuestionAnswer, QuestionOption, Quota,
SeatCategoryMapping, Voucher,
)
from pretix.base.models.event import SubEvent
from pretix.base.models.items import (
ItemAddOn, ItemBundle, ItemMetaValue, Questionnaire,
)
from pretix.base.models.items import ItemAddOn, ItemBundle, ItemMetaValue
from pretix.base.services.quotas import QuotaAvailability
from pretix.base.services.tickets import invalidate_cache
from pretix.base.signals import quota_availability
@@ -98,12 +94,7 @@ from pretix.helpers.models import modelcopy
from ...helpers import GroupConcat
from ...helpers.compat import CompatDeleteView
from ...helpers.i18n import i18n_all_from_gettext
from . import (
ChartContainingView, CreateView, PaginationMixin, TellParentFormMixin,
UpdateView,
)
from ...presale.views import prefetch_relevant_questionnaires
from . import ChartContainingView, CreateView, PaginationMixin, UpdateView
def has_truthy_attr(cls, attr):
@@ -129,10 +120,7 @@ class ItemList(ListView):
).select_related("tax_rule").annotate(
var_count=Count('variations'),
requires_seat=requires_seat,
).prefetch_related(
"category", "limit_sales_channels",
prefetch_relevant_questionnaires(None, None, questionnaire_lookup='questionnaires'),
).order_by(
).prefetch_related("category", "limit_sales_channels").order_by(
F('category__position').asc(nulls_first=True),
'category', 'position'
)
@@ -140,16 +128,6 @@ class ItemList(ListView):
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
ctx['sales_channels'] = self.request.organizer.sales_channels.all()
for item in ctx['items']:
qrows = [qc for qq in item.relevant_questionnaires for qc in qq.rows.all()]
item.attendee_data_asked = any(row.system_datafield for row in qrows)
item.attendee_data_required = item.attendee_data_asked and any(row.system_datafield and row.required for row in qrows)
item.custom_questions_asked = any(row.user_datafield_id for row in qrows)
item.questionnaire_names_html = format_html_join('<br>', '• {} {}{}', ((
q.internal_name,
mark_safe("<i class='fa fa-check-square'></i>") if q.ask_during_checkin else '',
mark_safe("<i class='fa fa-eye-slash'></i>") if q.hidden else '',
) for q in item.relevant_questionnaires))
items_by_category = {cat: list(items) for cat, items in groupby(ctx['items'], lambda item: item.category)}
ctx['cat_list'] = [(cat, items_by_category.get(cat, [])) for cat in [None, *self.request.event.categories.all()]]
return ctx
@@ -273,7 +251,7 @@ class CategoryDelete(EventPermissionRequiredMixin, CompatDeleteView):
})
class CategoryUpdate(TellParentFormMixin, EventPermissionRequiredMixin, UpdateView):
class CategoryUpdate(EventPermissionRequiredMixin, UpdateView):
model = ItemCategory
form_class = CategoryForm
template_name = 'pretixcontrol/items/category.html'
@@ -311,7 +289,7 @@ class CategoryUpdate(TellParentFormMixin, EventPermissionRequiredMixin, UpdateVi
return super().form_invalid(form)
class CategoryCreate(TellParentFormMixin, EventPermissionRequiredMixin, CreateView):
class CategoryCreate(EventPermissionRequiredMixin, CreateView):
model = ItemCategory
form_class = CategoryForm
template_name = 'pretixcontrol/items/category.html'
@@ -459,7 +437,66 @@ class QuestionList(ListView):
template_name = 'pretixcontrol/items/questions.html'
def get_queryset(self):
return self.request.event.questions.all()
return self.request.event.questions.prefetch_related('items')
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
questions = get_fake_attendee_questions(self.request.event.settings)
questions += list(ctx['questions'])
questions.sort(key=lambda q: q.position)
ctx['questions'] = questions
return ctx
@transaction.atomic
@event_permission_required("event.items:write")
@require_http_methods(["POST"])
def reorder_questions(request, organizer, event):
try:
ids = json.loads(request.body.decode('utf-8'))['ids']
except (JSONDecodeError, KeyError, ValueError):
return HttpResponseBadRequest("expected JSON: {ids:[]}")
qs = request.event.questions.filter(container_type=request.GET['container_type'])
# filter system_questions - normal questions are int/digit, system_questions strings
custom_question_ids = [i for i in ids if i.isdigit()]
input_questions = list(qs.filter(id__in=custom_question_ids))
if len(input_questions) != len(custom_question_ids):
raise Http404(_("Some of the provided object ids are invalid."))
if len(input_questions) != qs.count():
raise Http404(_("Not all objects have been selected."))
for q in input_questions:
pos = ids.index(str(q.pk))
if pos != q.position: # Save unneccessary UPDATE queries
q.position = pos
q.save(update_fields=['position'])
q.log_action(
'pretix.event.question.reordered', user=request.user, data={
'position': pos,
}
)
if request.GET['container_type'] == Question.ContainerType.ORDERPOSITION:
system_question_order = {}
for s in ('attendee_name_parts', 'attendee_email', 'company', 'street', 'zipcode', 'city', 'country'):
if s in ids:
system_question_order[s] = ids.index(s)
else:
system_question_order[s] = -1
request.event.settings.system_question_order = system_question_order
request.event.log_action(
'pretix.event.settings', user=request.user, data={
'system_question_order': system_question_order,
}
)
return HttpResponse()
class QuestionDelete(EventPermissionRequiredMixin, CompatDeleteView):
@@ -478,7 +515,7 @@ class QuestionDelete(EventPermissionRequiredMixin, CompatDeleteView):
def get_context_data(self, *args, **kwargs) -> dict:
context = super().get_context_data(*args, **kwargs)
# TODO(questionnaires) context['dependent'] = list(self.get_object().items.all())
context['dependent'] = list(self.get_object().items.all())
context['edit_url'] = reverse('control:event.items.questions.edit', kwargs={
'organizer': self.request.event.organizer.slug,
'event': self.request.event.slug,
@@ -577,7 +614,7 @@ class QuestionView(EventPermissionRequiredMixin, ChartContainingView, DetailView
question=self.object, orderposition__isnull=False,
)
qs = qs.filter(orderposition__in=opqs)
op_cnt = 0 # TODO opqs.filter(item__in=self.object.items.all()).count()
op_cnt = opqs.filter(item__in=self.object.items.all()).count()
if self.object.type == Question.TYPE_FILE:
qs = [
@@ -622,7 +659,7 @@ class QuestionView(EventPermissionRequiredMixin, ChartContainingView, DetailView
def get_context_data(self, **kwargs):
ctx = super().get_context_data()
# TODO(questionnaires) ctx['items'] = self.object.items.exists()
ctx['items'] = self.object.items.exists()
ctx['has_subevents'] = self.request.event.has_subevents
stats = self.get_answer_statistics()
ctx['stats'], ctx['total'] = stats
@@ -644,7 +681,7 @@ class QuestionView(EventPermissionRequiredMixin, ChartContainingView, DetailView
})
class QuestionUpdate(TellParentFormMixin, EventPermissionRequiredMixin, QuestionMixin, UpdateView):
class QuestionUpdate(EventPermissionRequiredMixin, QuestionMixin, UpdateView):
model = Question
form_class = QuestionForm
template_name = 'pretixcontrol/items/question_edit.html'
@@ -685,7 +722,7 @@ class QuestionUpdate(TellParentFormMixin, EventPermissionRequiredMixin, Question
return super().form_invalid(form)
class QuestionCreate(TellParentFormMixin, EventPermissionRequiredMixin, QuestionMixin, CreateView):
class QuestionCreate(EventPermissionRequiredMixin, QuestionMixin, CreateView):
model = Question
form_class = QuestionForm
template_name = 'pretixcontrol/items/question_edit.html'
@@ -729,26 +766,6 @@ class QuestionCreate(TellParentFormMixin, EventPermissionRequiredMixin, Question
return ret
def textchoices_to_json(choices, event):
return [(c.name, c.value, i18n_all_from_gettext(c.label, event.settings.locales)) for c in choices]
class QuestionnairesEditor(EventPermissionRequiredMixin, TemplateView):
permission = 'can_change_items'
template_name = 'pretixcontrol/items/questionnaires.html'
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
ctx['questionnaire_type_choices'] = textchoices_to_json(Questionnaire.QuestionnaireType, self.request.event)
ctx['system_question_choices'] = textchoices_to_json(QuestionnaireRow.SystemDatafield, self.request.event)
ctx['question_type_choices'] = textchoices_to_json(Question.FieldType, self.request.event)
ctx["locales"] = {
l: dict(settings.LANGUAGES).get(l, l)
for l in self.request.event.settings.get("locales")
}
return ctx
class QuotaQueryMixin:
@cached_property
@@ -1354,10 +1371,9 @@ class ItemCreate(EventPermissionRequiredMixin, MetaDataEditorMixin, CreateView):
initial['tax_rule'] = trs[0]
if self.copy_from:
fields = ('name', 'internal_name', 'category', 'admission', 'default_price', 'tax_rule')
fields = ('name', 'internal_name', 'category', 'admission', 'personalized', 'default_price', 'tax_rule')
for f in fields:
initial[f] = getattr(self.copy_from, f)
initial['questionnaires'] = self.copy_from.questionnaires.values_list('pk', flat=True)
initial['copy_from'] = self.copy_from
initial['has_variations'] = self.copy_from.variations.exists()
@@ -1391,7 +1407,7 @@ class ItemCreate(EventPermissionRequiredMixin, MetaDataEditorMixin, CreateView):
return super().form_invalid(form)
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
ctx = super().get_context_data()
ctx['meta_forms'] = self.meta_forms
return ctx
@@ -1399,11 +1415,9 @@ class ItemCreate(EventPermissionRequiredMixin, MetaDataEditorMixin, CreateView):
self.object = None
form = self.get_form()
if form.is_valid() and all([f.is_valid() for f in self.meta_forms]):
try:
return self.form_valid(form)
except ValidationError as e:
form.add_error(None, e)
return self.form_invalid(form)
return self.form_valid(form)
else:
return self.form_invalid(form)
class ItemUpdateGeneral(ItemDetailMixin, EventPermissionRequiredMixin, MetaDataEditorMixin, UpdateView):
@@ -1467,11 +1481,9 @@ class ItemUpdateGeneral(ItemDetailMixin, EventPermissionRequiredMixin, MetaDataE
self.get_object()
form = self.get_form()
if self.is_valid(form) and all([f.is_valid() for f in self.meta_forms]):
try:
return self.form_valid(form)
except ValidationError as exc:
form.add_error(None, exc)
return self.form_invalid(form)
return self.form_valid(form)
else:
return self.form_invalid(form)
def save_formset(self, key, log_base, attr='item', order=True, serializer=None,
rm_verb='removed'):
@@ -1520,6 +1532,7 @@ class ItemUpdateGeneral(ItemDetailMixin, EventPermissionRequiredMixin, MetaDataE
@transaction.atomic
def form_valid(self, form):
self.save_meta()
messages.success(self.request, _('Your changes have been saved.'))
change_data = {
k: form.cleaned_data.get(k)
@@ -1579,9 +1592,7 @@ class ItemUpdateGeneral(ItemDetailMixin, EventPermissionRequiredMixin, MetaDataE
else:
v.save()
response = super().form_valid(form)
messages.success(self.request, _('Your changes have been saved.'))
return response
return super().form_valid(form)
def form_invalid(self, form):
messages.error(self.request, _('We could not save your changes. See below for details.'))
@@ -1594,7 +1605,7 @@ class ItemUpdateGeneral(ItemDetailMixin, EventPermissionRequiredMixin, MetaDataE
return o
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
ctx = super().get_context_data()
ctx['plugin_forms'] = self.plugin_forms
ctx['meta_forms'] = self.meta_forms
ctx['formsets'] = self.formsets
+12 -11
View File
@@ -85,7 +85,7 @@ from pretix.base.models import (
)
from pretix.base.models.orders import (
CancellationRequest, OrderFee, OrderPayment, OrderPosition, OrderRefund,
PrintLog, QuestionnaireRenderer,
PrintLog,
)
from pretix.base.models.tax import ask_for_vat_id
from pretix.base.payment import PaymentException
@@ -143,7 +143,6 @@ from pretix.helpers.iter import chunked_iterable
from pretix.helpers.json import CustomJSONEncoder
from pretix.helpers.safedownload import check_token
from pretix.presale.signals import question_form_fields
from pretix.presale.views import prefetch_relevant_questionnaires
logger = logging.getLogger(__name__)
@@ -595,15 +594,13 @@ class OrderDetail(OrderView):
def get_items(self):
queryset = self.object.all_positions
orderpos = queryset.order_by(
cartpos = queryset.order_by(
'item', 'variation'
).select_related(
'item', 'variation', 'addon_to', 'tax_rule', 'used_membership', 'used_membership__membership_type',
'discount',
).prefetch_related(
prefetch_relevant_questionnaires(None, None),
#'item__questionnaires',
'issued_gift_cards', 'owned_gift_cards', 'linked_media', # TODO(questionnaires) : item__questions gibts nicht mehr
'item__questions', 'issued_gift_cards', 'owned_gift_cards', 'linked_media',
Prefetch('answers', queryset=QuestionAnswer.objects.prefetch_related('options').select_related('question')),
Prefetch('all_checkins', queryset=Checkin.all.select_related('list', 'gate').order_by('datetime')),
Prefetch('print_logs', queryset=PrintLog.objects.select_related('device').order_by('datetime')),
@@ -611,7 +608,7 @@ class OrderDetail(OrderView):
).order_by('positionid')
positions = []
for p in orderpos:
for p in cartpos:
responses = question_form_fields.send(sender=self.request.event, position=p)
p.additional_fields = []
data = p.meta_info_data
@@ -623,9 +620,13 @@ class OrderDetail(OrderView):
'question': value.label
})
p.has_questions = p.additional_fields or p.item.questionnaires.all()
qrows = list(copy.copy(qc) for qq in p.item.relevant_questionnaires for qc in qq.rows.all())
p.rendered_questions = QuestionnaireRenderer(qrows=qrows, system_answers=p.system_answers, answerlist=p.answers.all())
p.has_questions = (
p.additional_fields or
(p.item.ask_attendee_data and self.request.event.settings.attendee_names_asked) or
(p.item.ask_attendee_data and self.request.event.settings.attendee_emails_asked) or
p.item.questions.all()
)
p.cache_answers()
p.order = self.order
positions.append(p)
@@ -634,7 +635,7 @@ class OrderDetail(OrderView):
return {
'positions': positions,
'raw': orderpos,
'raw': cartpos,
'total': self.object.total,
'fees': self.object.all_fees.all(),
'net_total': self.object.net_total,
-12
View File
@@ -32,7 +32,6 @@ from django.conf import settings
from django.utils import translation
from django.utils.formats import get_format
from django.utils.translation import to_locale
from i18nfield.strings import LazyI18nString
date_conversion_to_moment = {
'%a': 'ddd',
@@ -245,14 +244,3 @@ def parse_date_localized(date_str) -> Optional[datetime]:
except (ValueError, TypeError):
continue
return dt
def i18n_all_from_gettext(gettext_str, locales):
return i18n_all(LazyI18nString.from_gettext(gettext_str).data, locales)
def i18n_all(data, locales):
out = {}
for locale in locales:
out[locale] = data[locale]
return out
-17
View File
@@ -29,20 +29,3 @@ def chunked_iterable(iterable, size):
if not chunk:
break
yield chunk
def sort_groupby(data, group_key, inner_sort_key=None):
"""
Groups data by group_key, returns a list of (group_key, list). The outer list is
sorted by group_key, all inner lists are sorted by inner_sort_key.
"""
sort_key = group_key if inner_sort_key is None else lambda d: (group_key(d), inner_sort_key(d))
return [(group, list(items)) for group, items in itertools.groupby(sorted(data, key=sort_key), group_key)]
def sort_groupby_exp(data, group_key, inner_sort_key=None):
"""
Same as sort_groupby, but items are passed into the key functions as *item, so tuples can be destructed easily.
"""
sort_key = (lambda d: group_key(*d)) if inner_sort_key is None else lambda d: (group_key(*d), inner_sort_key(*d))
return [(group, list(items)) for group, items in itertools.groupby(sorted(data, key=sort_key), lambda d: group_key(*d))]
-104
View File
@@ -19,18 +19,12 @@
# You should have received a copy of the GNU Affero General Public License along with this program. If not, see
# <https://www.gnu.org/licenses/>.
#
import collections
import copy
from decimal import Decimal
from django.core.files import File
from django.db import models
from django.db.models.fields import DecimalField
from django.db.models.fields.related_descriptors import ForeignKeyDeferredAttribute, ForwardManyToOneDescriptor, \
ManyToManyDescriptor, \
ReverseManyToOneDescriptor
from pretix.settings import DEBUG
class Thumbnail(models.Model):
@@ -54,58 +48,6 @@ def modelcopy(obj: models.Model, **kwargs):
return n
def copy_objects(qs, to, translate=(), child_relations=(), obj_map=None):
# Validate arguments
for rel, kwargs in child_relations:
assert isinstance(getattr(qs.model, rel), ReverseManyToOneDescriptor)
for (rel, key, map) in translate:
assert isinstance(map, collections.abc.Mapping)
assert isinstance(getattr(qs.model, rel), (ReverseManyToOneDescriptor, ManyToManyDescriptor, ForwardManyToOneDescriptor))
if obj_map is None:
obj_map = {}
for o in qs:
# Fetch data for child relations
inst_child_rels = []
for rel, kwargs in child_relations:
qs = getattr(o, rel).all()
bool(qs) # ensure query set is fetched
inst_child_rels.append((getattr(o, rel).field, qs, kwargs))
# Fetch data and apply translation (via mapping dict) for translated relations
inst_trans_multi_rels = []
inst_trans_single_rels = []
for (rel, key, map) in translate:
if isinstance(getattr(type(o), rel), (ReverseManyToOneDescriptor, ManyToManyDescriptor)):
inst_trans_multi_rels.append((rel, [map[key] for key in getattr(o, rel).all().values_list(key, flat=True) if map[key] is not None]))
elif isinstance(getattr(type(o), rel), ForwardManyToOneDescriptor):
if key == 'id' and isinstance(getattr(type(o), f'{rel}_id'), ForeignKeyDeferredAttribute):
value = getattr(o, f'{rel}_id')
inst_trans_single_rels.append((rel, map[value] if value is not None else None))
else:
rel_obj = getattr(o, rel)
inst_trans_single_rels.append((rel, map[getattr(rel_obj, key)] if rel_obj is not None else None))
# Clone this object
obj_map[o.pk] = o
o.pk = None
o._prefetched_objects_cache = {}
if to:
setattr(o, to[0], to[1])
for (field_name, rel_obj) in inst_trans_single_rels:
setattr(o, field_name, rel_obj)
o.save(force_insert=True)
if hasattr(o, 'log_action'):
o.log_action('pretix.object.cloned')
# Copy objects from child relations
for (field, children, kwargs) in inst_child_rels:
copy_objects(children, to=(field.name, o), **kwargs)
for (rel_name, rel_objs) in inst_trans_multi_rels:
getattr(o, rel_name).add(*rel_objs)
return obj_map
# django 5 contains this in django.utils.choices.flatten_choices
def flatten_choices(choices):
"""Flatten choices by removing nested values."""
@@ -144,49 +86,3 @@ class NormalizedDecimalField(DecimalField):
if value is not None:
value = _normalize_decimal(value)
return value
def get_prefetch_cache(related_manager):
if hasattr(related_manager, 'get_prefetch_cache'):
return related_manager.get_prefetch_cache()
else:
try:
return related_manager.instance._prefetched_objects_cache[
related_manager.field.remote_field.cache_name
]
except (AttributeError, KeyError):
return None
def is_prefetched(related_manager):
return get_prefetch_cache(related_manager) is not None
def find_first_with_cache(related_manager, **filter_kwargs):
if is_prefetched(related_manager):
for candidate in related_manager.all():
if _evaluate_simple_filter(candidate, **filter_kwargs):
return candidate
else:
result = related_manager.filter(**filter_kwargs).first()
if result and DEBUG:
assert _evaluate_simple_filter(result, **filter_kwargs) # ensure we only build filters that are compatible with _evaluate_simple_filter
return result
def filter_with_cache(related_manager, **filter_kwargs):
qs = related_manager.filter(**filter_kwargs)
if is_prefetched(related_manager):
qs._result_cache = [obj for obj in related_manager.all() if _evaluate_simple_filter(obj, **filter_kwargs)]
return qs
def _evaluate_simple_filter(obj, **filter_kwargs):
for key, expected_value in filter_kwargs.items():
path = key.split('__')
o = obj
for p in path:
o = getattr(o, p)
if o != expected_value:
return False
return True
+49 -81
View File
@@ -8,8 +8,8 @@ msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-09-30 07:26+0000\n"
"PO-Revision-Date: 2026-09-28 11:01+0000\n"
"Last-Translator: Tim <plicnetwork@gmail.com>\n"
"PO-Revision-Date: 2026-10-03 23:00+0000\n"
"Last-Translator: Oksigenia <github@oksigenia.cc>\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.9.1\n"
"X-Generator: Weblate 2026.10\n"
#: pretix/_base_settings.py
msgid "English"
@@ -1793,16 +1793,12 @@ msgid "Transmission type"
msgstr "Tipo de transmisión"
#: pretix/base/exporters/invoices.py
#, fuzzy
#| msgid "Transmission type"
msgid "Transmission status"
msgstr "Tipo de transmisión"
msgstr "Estado de la transmisión"
#: pretix/base/exporters/invoices.py
#, fuzzy
#| msgid "Transmission type"
msgid "Transmission date"
msgstr "Tipo de transmisión"
msgstr "Fecha de emisión"
#: pretix/base/exporters/invoices.py
msgid "Cancellation"
@@ -3289,7 +3285,7 @@ msgstr ""
#: pretix/base/forms/validators.py pretix/control/views/event.py
#, python-format
msgid "Invalid placeholder: {%(value)s}"
msgstr "Marcador de posición no válido: {%(value)ss}"
msgstr "Marcador de posición no válido: {%(value)s}"
#: pretix/base/forms/widgets.py
#, python-format
@@ -4458,10 +4454,8 @@ msgid "Initialization date"
msgstr "Fecha de inicialización"
#: pretix/base/models/devices.py
#, fuzzy
#| msgid "Save to profile"
msgid "Security profile"
msgstr "Guardar en perfil"
msgstr "Perfil de seguridad"
#: pretix/base/models/discount.py
msgctxt "subevent"
@@ -5904,10 +5898,8 @@ msgid "Maximum value"
msgstr "Valor máximo"
#: pretix/base/models/items.py
#, fuzzy
#| msgid "Maximum length"
msgid "Minimum length"
msgstr "Longitud máxima"
msgstr "Longitud mínima"
#: pretix/base/models/items.py
msgid "Maximum length"
@@ -5978,10 +5970,8 @@ msgid "The maximum value must not be lower than the minimum value."
msgstr "El valor máximo no debe ser inferior al mínimo."
#: pretix/base/models/items.py
#, fuzzy
#| msgid "The maximum value must not be lower than the minimum value."
msgid "The maximum length must not be shorter than the minimum length."
msgstr "El valor máximo no debe ser inferior al mínimo."
msgstr "La longitud máxima no debe ser inferior a la longitud mínima."
#: pretix/base/models/items.py
msgid ""
@@ -10581,10 +10571,8 @@ msgstr ""
"después de la `Última fecha de pagos' configurada anteriormente."
#: pretix/base/settings.py
#, fuzzy
#| msgid "Generate invoices for Sales channels"
msgid "Allow postponed payment choice for sales channels"
msgstr "Generar facturas para canales de ventas"
msgstr "Permitir la opción de pago aplazado en los canales de venta"
#: pretix/base/settings.py
msgid ""
@@ -10592,6 +10580,9 @@ 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 ""
"Si en un canal de venta se permite el pago aplazado, los clientes pueden "
"completar su pedido sin seleccionar una forma de pago. Esto resulta útil "
"cuando los pedidos no los realiza la misma persona que efectúa el pago."
#: pretix/base/settings.py
msgid "Show start date"
@@ -16860,7 +16851,7 @@ msgstr "tercero"
#: pretix/control/forms/rrule.py
msgctxt "rrule"
msgid "fourth"
msgstr ""
msgstr "cuarto"
#: pretix/control/forms/rrule.py
msgctxt "rrule"
@@ -17993,28 +17984,20 @@ msgid "Queued emails have been aborted."
msgstr "Los correos electrónicos en cola se han cancelado."
#: pretix/control/logdisplay.py
#, fuzzy
#| msgid "The property has been created."
msgid "An organizer meta property has been created."
msgstr "La propiedad ha sido creada."
msgstr "Se ha creado una metapropiedad de organizador."
#: pretix/control/logdisplay.py
#, fuzzy
#| msgid "The selected property has been deleted."
msgid "An organizer meta property has been deleted."
msgstr "La propiedad seleccionada ha sido eliminada."
msgstr "Se ha eliminado una metapropiedad del organizador."
#: pretix/control/logdisplay.py
#, fuzzy
#| msgid "The organizer has been changed."
msgid "An organizer meta property has been changed."
msgstr "El pedido se ha cambiado."
msgstr "Se ha modificado una metapropiedad del organizador."
#: pretix/control/logdisplay.py
#, fuzzy
#| msgid "The product has been reordered."
msgid "An organizer meta property has been reordered."
msgstr "El producto se ha pedido de nuevo."
msgstr "Se ha cambiado el orden de una metapropiedad del organizador."
#: pretix/control/logdisplay.py
msgid "Gift card acceptance for another organizer has been added."
@@ -18228,6 +18211,8 @@ msgstr "Se ha generado un código de emergencia de doble factor."
#: pretix/control/logdisplay.py
msgid "Drift and throttle values for two-factor devices have been reset."
msgstr ""
"Se han restablecido los valores de deriva y aceleración para los "
"dispositivos de dos factores."
#: pretix/control/logdisplay.py
#, python-brace-format
@@ -19180,10 +19165,8 @@ msgid "Cancel"
msgstr "Cancelar"
#: pretix/control/templates/pretixcontrol/auth/oauth_authorization.html
#, fuzzy
#| msgid "Authorized apps"
msgid "Authorize"
msgstr "Aplicaciones autorizadas"
msgstr "Autorizar"
#: pretix/control/templates/pretixcontrol/auth/oauth_authorization.html
msgid "Error:"
@@ -22071,14 +22054,10 @@ msgstr ""
"hacer referencia a este evento."
#: pretix/control/templates/pretixcontrol/events/create_basics.html
#, fuzzy
#| msgid ""
#| "We strongly recommend against using short forms of more then 16 "
#| "characters."
msgid ""
"We strongly recommend against using short forms of more than 16 characters."
msgstr ""
"Recomendamos encarecidamente no utilizar formularios cortos de más de 16 "
"Recomendamos encarecidamente no utilizar abreviaturas de más de 16 "
"caracteres."
#: pretix/control/templates/pretixcontrol/events/create_basics.html
@@ -27957,27 +27936,23 @@ msgstr "Autenticación backend"
#: pretix/control/templates/pretixcontrol/users/form.html
msgid "Reset drift and throttle"
msgstr ""
msgstr "Restablecer la desviación y el control"
#: pretix/control/templates/pretixcontrol/users/form.html
#, fuzzy
#| msgid "Disable two-factor authentication"
msgid "Available two-factor authentication methods"
msgstr "Desactivar la autenticación de dos factores"
msgstr "Métodos de autenticación de dos factores disponibles"
#: pretix/control/templates/pretixcontrol/users/form.html
#, fuzzy, python-format
#| msgid "Expired since %(date)s"
#, python-format
msgid "1 failed attempt since %(date)s"
msgid_plural "%(cnt)s failed attempts since %(date)s"
msgstr[0] "Vencido desde el %(date)s"
msgstr[1] "Vencido desde el %(date)s"
msgstr[0] "1 intento fallido desde %(date)s"
msgstr[1] "%(cnt)s intentos fallidos desde el %(date)s"
#: pretix/control/templates/pretixcontrol/users/form.html
#, fuzzy, python-format
#| msgid "Valid until %(date)s"
#, python-format
msgid "Currently locked until %(date)s"
msgstr "Válido hasta el %(date)s"
msgstr "Actualmente bloqueado hasta el %(date)s"
#: pretix/control/templates/pretixcontrol/users/form.html
msgid "Team memberships"
@@ -28519,20 +28494,18 @@ msgid "Invalid code, please try again."
msgstr "Código inválido, por favor inténtelo de nuevo."
#: pretix/control/views/auth.py
#, fuzzy, python-brace-format
#| msgid "Invalid code, please try again."
#, python-brace-format
msgid "Invalid code. Please try again after waiting {value} minute."
msgid_plural "Invalid code. Please try again after waiting {value} minutes."
msgstr[0] "Código inválido, por favor inténtelo de nuevo."
msgstr[1] "Código inválido, por favor inténtelo de nuevo."
msgstr[0] "Código no válido. Inténtalo de nuevo tras esperar {value} minutos."
msgstr[1] "ódigo no válido. Inténtalo de nuevo tras esperar {value} minutos."
#: pretix/control/views/auth.py
#, fuzzy, python-brace-format
#| msgid "Invalid code, please try again."
#, python-brace-format
msgid "Invalid code. Please try again after waiting {value} second."
msgid_plural "Invalid code. Please try again after waiting {value} seconds."
msgstr[0] "Código inválido, por favor inténtelo de nuevo."
msgstr[1] "Código inválido, por favor inténtelo de nuevo."
msgstr[0] "Código no válido. Inténtalo de nuevo tras esperar {value} segundo."
msgstr[1] "Código no válido. Inténtalo de nuevo tras esperar {value} segundos."
#: pretix/control/views/checkin.py
msgid "The selected check-ins have been reverted."
@@ -29405,10 +29378,8 @@ msgid "You entered an order in an event with a different currency."
msgstr "Ha introducido un pedido en un evento con una moneda diferente."
#: pretix/control/views/orders.py
#, fuzzy
#| msgid "You entered an order in an event with a different currency."
msgid "You entered an order in an event that you do not have access to."
msgstr "Ha introducido un pedido en un evento con una moneda diferente."
msgstr "Ha introducido un pedido en un evento al que no tienes acceso."
#: pretix/control/views/orders.py
msgid ""
@@ -30296,10 +30267,9 @@ msgstr ""
"código de emergencia anterior para este usuario permanecerá activo."
#: pretix/control/views/users.py
#, fuzzy
#| msgid "The password has been reset."
msgid "The drift values for TOTP devices have been reset."
msgstr "La contraseña ha sido reiniciada."
msgstr ""
"Se han restablecido los valores de desviación para los dispositivos TOTP."
#: pretix/control/views/users.py
msgid "The new user has been created."
@@ -30314,14 +30284,12 @@ msgid "Bypass quota"
msgstr "Cuota de bypass"
#: pretix/control/views/vouchers.py
#, fuzzy
#| msgid "Widget"
msgid "Budget"
msgstr "Widget"
msgstr "Presupuesto"
#: pretix/control/views/vouchers.py
msgid "Budget used"
msgstr ""
msgstr "Presupuesto utilizado"
#: pretix/control/views/vouchers.py
msgid "The requested voucher does not exist."
@@ -35022,29 +34990,29 @@ msgid ""
"Not sure yet? You can complete your order first and then select a payment "
"method later."
msgstr ""
"¿Aún no estás seguro? Puedes completar primero tu pedido y seleccionar la "
"forma de pago más tarde."
#: pretix/presale/templates/pretixpresale/event/checkout_payment.html
msgid ""
"To do so, please first remove the payment methods you already selected above."
msgstr ""
"Para ello, elimina primero los métodos de pago que ya hayas seleccionado "
"anteriormente."
#: pretix/presale/templates/pretixpresale/event/checkout_payment.html
#, fuzzy, python-format
#| msgid "Your event needs to be over to use this feature."
#, python-format
msgid "Your payment needs to be completed within %(minutes)s minutes."
msgstr "Su evento debe haber terminado para utilizar esta función."
msgstr "Su pago debe completarse en un plazo de %(minutes)s minutos."
#: pretix/presale/templates/pretixpresale/event/checkout_payment.html
#, fuzzy, python-format
#| msgid "Your event needs to be over to use this feature."
#, python-format
msgid "Your payment needs to be completed by %(deadline)s."
msgstr "Su evento debe haber terminado para utilizar esta función."
msgstr "Su pago debe completarse antes de %(deadline)s."
#: pretix/presale/templates/pretixpresale/event/checkout_payment.html
#, fuzzy
#| msgid "Proceed with reset"
msgid "Proceed without selection"
msgstr "Continuar con el restablecimiento"
msgstr "Continuar sin seleccionar nada"
#: pretix/presale/templates/pretixpresale/event/checkout_questions.html
msgid "Before we continue, we need you to answer some questions."
+4 -4
View File
@@ -8,8 +8,8 @@ msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-09-30 07:26+0000\n"
"PO-Revision-Date: 2026-06-29 17:00+0000\n"
"Last-Translator: CVZ-es <damien.bremont@casadevelazquez.org>\n"
"PO-Revision-Date: 2026-10-03 23:00+0000\n"
"Last-Translator: Oksigenia <github@oksigenia.cc>\n"
"Language-Team: Spanish <https://translate.pretix.eu/projects/pretix/pretix-"
"js/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.6.1\n"
"X-Generator: Weblate 2026.10\n"
#: pretix/plugins/banktransfer/static/pretixplugins/banktransfer/ui.js
msgid "Marked as paid"
@@ -780,7 +780,7 @@ msgstr "El organizador retiene %(currency)s %(amount)s"
#: pretix/static/pretixpresale/js/ui/main.js
msgid "You get %(currency)s %(amount)s back"
msgstr "Se le devolverá %(moneda)s %(cantidad)s"
msgstr "Se le devolverá %(currency)s %(amount)s"
#: pretix/static/pretixpresale/js/ui/main.js
msgid "Please enter the amount the organizer can keep."
+51 -81
View File
@@ -4,10 +4,10 @@ msgstr ""
"Project-Id-Version: 1\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-09-30 07:26+0000\n"
"PO-Revision-Date: 2026-09-30 07:25+0000\n"
"PO-Revision-Date: 2026-10-01 09:28+0000\n"
"Last-Translator: CVZ-es <damien.bremont@casadevelazquez.org>\n"
"Language-Team: French <https://translate.pretix.eu/projects/pretix/pretix/fr/"
">\n"
"Language-Team: French <https://translate.pretix.eu/projects/pretix/pretix/"
"fr/>\n"
"Language: fr\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
@@ -1793,16 +1793,12 @@ msgid "Transmission type"
msgstr "Type de transmission"
#: pretix/base/exporters/invoices.py
#, fuzzy
#| msgid "Transmission type"
msgid "Transmission status"
msgstr "Type de transmission"
msgstr "État de la transmission"
#: pretix/base/exporters/invoices.py
#, fuzzy
#| msgid "Transmission type"
msgid "Transmission date"
msgstr "Type de transmission"
msgstr "Date de transmission"
#: pretix/base/exporters/invoices.py
msgid "Cancellation"
@@ -4468,10 +4464,8 @@ msgid "Initialization date"
msgstr "Date d'initialisation"
#: pretix/base/models/devices.py
#, fuzzy
#| msgid "Save to profile"
msgid "Security profile"
msgstr "Enregistrer dans le profil"
msgstr "Profil de sécurité"
#: pretix/base/models/discount.py
msgctxt "subevent"
@@ -5925,10 +5919,8 @@ msgid "Maximum value"
msgstr "Valeur maximale"
#: pretix/base/models/items.py
#, fuzzy
#| msgid "Maximum length"
msgid "Minimum length"
msgstr "Longueur maximale"
msgstr "Longueur minimale"
#: pretix/base/models/items.py
msgid "Maximum length"
@@ -6000,10 +5992,9 @@ msgid "The maximum value must not be lower than the minimum value."
msgstr "La valeur maximale ne doit pas être inférieure à la valeur minimale."
#: pretix/base/models/items.py
#, fuzzy
#| msgid "The maximum value must not be lower than the minimum value."
msgid "The maximum length must not be shorter than the minimum length."
msgstr "La valeur maximale ne doit pas être inférieure à la valeur minimale."
msgstr ""
"La longueur maximale ne doit pas être inférieure à la longueur minimale."
#: pretix/base/models/items.py
msgid ""
@@ -10647,10 +10638,8 @@ msgstr ""
"accepté après la 'dernière date de paiement' configurée ci-dessus."
#: pretix/base/settings.py
#, fuzzy
#| msgid "Generate invoices for Sales channels"
msgid "Allow postponed payment choice for sales channels"
msgstr "Générer des factures pour les canaux de vente"
msgstr "Autoriser l'option de paiement différé pour les canaux de vente"
#: pretix/base/settings.py
msgid ""
@@ -10658,6 +10647,10 @@ 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 ""
"Si le paiement différé est autorisé sur un canal de vente, les clients "
"peuvent finaliser leur commande sans sélectionner de mode de paiement. Cette "
"fonctionnalité est utile lorsque la commande n'est pas passée par la même "
"personne que celle qui effectue le paiement."
#: pretix/base/settings.py
msgid "Show start date"
@@ -17017,7 +17010,7 @@ msgstr "troisième"
#: pretix/control/forms/rrule.py
msgctxt "rrule"
msgid "fourth"
msgstr ""
msgstr "quatrième"
#: pretix/control/forms/rrule.py
msgctxt "rrule"
@@ -18137,28 +18130,20 @@ msgid "Queued emails have been aborted."
msgstr "Les e-mails en attente ont été annulés."
#: pretix/control/logdisplay.py
#, fuzzy
#| msgid "The property has been created."
msgid "An organizer meta property has been created."
msgstr "La propriété a été créée."
msgstr "Une méta-propriété d'organisateur a été créée."
#: pretix/control/logdisplay.py
#, fuzzy
#| msgid "The selected property has been deleted."
msgid "An organizer meta property has been deleted."
msgstr "La propriété sélectionnée a été supprimée."
msgstr "Une méta-propriété d'organisateur a été supprimée."
#: pretix/control/logdisplay.py
#, fuzzy
#| msgid "The organizer has been changed."
msgid "An organizer meta property has been changed."
msgstr "L’organisateur a été modifié."
msgstr "Une méta-propriété d'organisateur a été modifiée."
#: pretix/control/logdisplay.py
#, fuzzy
#| msgid "The product has been reordered."
msgid "An organizer meta property has been reordered."
msgstr "Le produit a été commandé à nouveau."
msgstr "Une méta-propriété d'organisateur a été réorganisée."
#: pretix/control/logdisplay.py
msgid "Gift card acceptance for another organizer has been added."
@@ -18374,6 +18359,8 @@ msgstr "Un code d'urgence à deux facteurs a été généré."
#: pretix/control/logdisplay.py
msgid "Drift and throttle values for two-factor devices have been reset."
msgstr ""
"Les valeurs de déviation et de puissance pour les appareils à deux facteurs "
"ont été réinitialisées."
#: pretix/control/logdisplay.py
#, python-brace-format
@@ -19322,10 +19309,8 @@ msgid "Cancel"
msgstr "Annuler"
#: pretix/control/templates/pretixcontrol/auth/oauth_authorization.html
#, fuzzy
#| msgid "Authorized apps"
msgid "Authorize"
msgstr "App. autorisées"
msgstr "Autoriser"
#: pretix/control/templates/pretixcontrol/auth/oauth_authorization.html
msgid "Error:"
@@ -22231,15 +22216,11 @@ msgstr ""
"comme abréviations pour faire référence à cet événement."
#: pretix/control/templates/pretixcontrol/events/create_basics.html
#, fuzzy
#| msgid ""
#| "We strongly recommend against using short forms of more then 16 "
#| "characters."
msgid ""
"We strongly recommend against using short forms of more than 16 characters."
msgstr ""
"Nous vous déconseillons fortement d'utiliser des formulaires courts de plus "
"de 16 caractères."
"Nous déconseillons vivement d'utiliser des abréviations de plus de 16 "
"caractères."
#: pretix/control/templates/pretixcontrol/events/create_basics.html
msgid "Display settings"
@@ -28171,27 +28152,23 @@ msgstr "Backend d’authentification"
#: pretix/control/templates/pretixcontrol/users/form.html
msgid "Reset drift and throttle"
msgstr ""
msgstr "Réinitialisation de la déviation et de la puissance"
#: pretix/control/templates/pretixcontrol/users/form.html
#, fuzzy
#| msgid "Disable two-factor authentication"
msgid "Available two-factor authentication methods"
msgstr "Désactiver l'authentification à deux facteurs"
msgstr "Méthodes d'authentification à deux facteurs disponibles"
#: pretix/control/templates/pretixcontrol/users/form.html
#, fuzzy, python-format
#| msgid "Expired since %(date)s"
#, python-format
msgid "1 failed attempt since %(date)s"
msgid_plural "%(cnt)s failed attempts since %(date)s"
msgstr[0] "Expiré depuis le %(date)s"
msgstr[1] "Expiré depuis le %(date)s"
msgstr[0] "1 tentative infructueuse depuis %(date)s"
msgstr[1] "%(cnt)s tentatives infructueuses depuis le %(date)s"
#: pretix/control/templates/pretixcontrol/users/form.html
#, fuzzy, python-format
#| msgid "Valid until %(date)s"
#, python-format
msgid "Currently locked until %(date)s"
msgstr "Valable jusqu'au %(date)s"
msgstr "Actuellement verrouillé jusqu'au %(date)s"
#: pretix/control/templates/pretixcontrol/users/form.html
msgid "Team memberships"
@@ -28737,20 +28714,19 @@ msgid "Invalid code, please try again."
msgstr "Code invalide, veuillez réessayer."
#: pretix/control/views/auth.py
#, fuzzy, python-brace-format
#| msgid "Invalid code, please try again."
#, python-brace-format
msgid "Invalid code. Please try again after waiting {value} minute."
msgid_plural "Invalid code. Please try again after waiting {value} minutes."
msgstr[0] "Code invalide, veuillez réessayer."
msgstr[1] "Code invalide, veuillez réessayer."
msgstr[0] "Code invalide. Veuillez réessayer après avoir patienté {value} minute."
msgstr[1] "Code invalide. Veuillez réessayer après avoir patienté {value} minutes."
#: pretix/control/views/auth.py
#, fuzzy, python-brace-format
#| msgid "Invalid code, please try again."
#, python-brace-format
msgid "Invalid code. Please try again after waiting {value} second."
msgid_plural "Invalid code. Please try again after waiting {value} seconds."
msgstr[0] "Code invalide, veuillez réessayer."
msgstr[1] "Code invalide, veuillez réessayer."
msgstr[0] "Code invalide. Veuillez réessayer après avoir patienté {value} seconde."
msgstr[1] ""
"Code invalide. Veuillez réessayer après avoir patienté {value} secondes."
#: pretix/control/views/checkin.py
msgid "The selected check-ins have been reverted."
@@ -29632,11 +29608,9 @@ msgstr ""
"Vous avez passé une commande dans un événement dont la devise est différente."
#: pretix/control/views/orders.py
#, fuzzy
#| msgid "You entered an order in an event with a different currency."
msgid "You entered an order in an event that you do not have access to."
msgstr ""
"Vous avez passé une commande dans un événement dont la devise est différente."
"Vous avez saisi une commande dans un événement auquel vous n'avez pas accès."
#: pretix/control/views/orders.py
msgid ""
@@ -30535,10 +30509,8 @@ msgstr ""
"d'urgence précédents de cet utilisateur sont toujours actifs."
#: pretix/control/views/users.py
#, fuzzy
#| msgid "The password has been reset."
msgid "The drift values for TOTP devices have been reset."
msgstr "Le mot de passe a été réinitialisé."
msgstr "Les valeurs de dérive des appareils TOTP ont été réinitialisées."
#: pretix/control/views/users.py
msgid "The new user has been created."
@@ -30553,14 +30525,12 @@ msgid "Bypass quota"
msgstr "Outrepasser le quota"
#: pretix/control/views/vouchers.py
#, fuzzy
#| msgid "Widget"
msgid "Budget"
msgstr "Widget"
msgstr "Budget"
#: pretix/control/views/vouchers.py
msgid "Budget used"
msgstr ""
msgstr "Budget utilisé"
#: pretix/control/views/vouchers.py
msgid "The requested voucher does not exist."
@@ -35309,29 +35279,29 @@ msgid ""
"Not sure yet? You can complete your order first and then select a payment "
"method later."
msgstr ""
"Vous hésitez encore ? Vous pouvez d'abord finaliser votre commande, puis "
"choisir un mode de paiement ultérieurement."
#: pretix/presale/templates/pretixpresale/event/checkout_payment.html
msgid ""
"To do so, please first remove the payment methods you already selected above."
msgstr ""
"Pour ce faire, veuillez d'abord supprimer les moyens de paiement que vous "
"avez déjà sélectionnés ci-dessus."
#: pretix/presale/templates/pretixpresale/event/checkout_payment.html
#, fuzzy, python-format
#| msgid "The payment has to be completed before %(date)s."
#, python-format
msgid "Your payment needs to be completed within %(minutes)s minutes."
msgstr "Le paiement doit être effectué avant le %(date)s."
msgstr "otre paiement doit être effectué dans les %(minutes)s minutes."
#: pretix/presale/templates/pretixpresale/event/checkout_payment.html
#, fuzzy, python-format
#| msgid "The payment has to be completed before %(date)s."
#, python-format
msgid "Your payment needs to be completed by %(deadline)s."
msgstr "Le paiement doit être effectué avant le %(date)s."
msgstr "Votre paiement doit être effectué avant le %(deadline)s."
#: pretix/presale/templates/pretixpresale/event/checkout_payment.html
#, fuzzy
#| msgid "Proceed with reset"
msgid "Proceed without selection"
msgstr "Procéder à la réinitialisation"
msgstr "Continuer sans sélectionner"
#: pretix/presale/templates/pretixpresale/event/checkout_questions.html
msgid "Before we continue, we need you to answer some questions."
+11 -33
View File
@@ -8,7 +8,7 @@ msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-09-30 07:26+0000\n"
"PO-Revision-Date: 2026-08-01 21:00+0000\n"
"PO-Revision-Date: 2026-09-30 17:00+0000\n"
"Last-Translator: szurofkamarciidfbe08444ef04788 <szurofkamarcii@gmail.com>\n"
"Language-Team: Hungarian <https://translate.pretix.eu/projects/pretix/pretix/"
"hu/>\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.7.1\n"
"X-Generator: Weblate 2026.9.1\n"
#: pretix/_base_settings.py
msgid "English"
@@ -93,7 +93,7 @@ msgstr "Héber"
#: pretix/_base_settings.py
msgid "Hungarian"
msgstr ""
msgstr "Magyar"
#: pretix/_base_settings.py
msgid "Indonesian"
@@ -426,10 +426,8 @@ msgid "You cannot exchange a medium for a medium."
msgstr "Nem cserélhet adathordozót adathordozóra."
#: pretix/api/views/checkin.py
#, fuzzy
#| msgid "Product does not support medium exchange."
msgid "You cannot simulate a medium exchange."
msgstr "A termék nem támogatja az adathordozó-cserét."
msgstr "Az adathordozó szimuláció nem engedélyezett."
#: pretix/api/views/oauth.py pretix/control/logdisplay.py
#, python-brace-format
@@ -1779,16 +1777,12 @@ msgid "Transmission type"
msgstr "Továbbítás típusa"
#: pretix/base/exporters/invoices.py
#, fuzzy
#| msgid "Transmission type"
msgid "Transmission status"
msgstr "Továbbítás típusa"
msgstr "Továbbítás állapot"
#: pretix/base/exporters/invoices.py
#, fuzzy
#| msgid "Transmission type"
msgid "Transmission date"
msgstr "Továbbítás típusa"
msgstr "Továbbítás dátum"
#: pretix/base/exporters/invoices.py
msgid "Cancellation"
@@ -3078,9 +3072,6 @@ msgid "Street"
msgstr "Utca"
#: pretix/base/forms/questions.py
#, fuzzy
#| msgctxt "address"
#| msgid "State"
msgid "State"
msgstr "Állam/tartomány"
@@ -4429,10 +4420,8 @@ msgid "Initialization date"
msgstr "Inicializálás dátuma"
#: pretix/base/models/devices.py
#, fuzzy
#| msgid "Save to profile"
msgid "Security profile"
msgstr "Mentés a profilhoz"
msgstr "Biztonsági profil"
#: pretix/base/models/discount.py
msgctxt "subevent"
@@ -5864,10 +5853,8 @@ msgid "Maximum value"
msgstr "Maximális érték"
#: pretix/base/models/items.py
#, fuzzy
#| msgid "Maximum length"
msgid "Minimum length"
msgstr "Maximális hossz"
msgstr "Minimum hossz"
#: pretix/base/models/items.py
msgid "Maximum length"
@@ -5938,10 +5925,8 @@ msgid "The maximum value must not be lower than the minimum value."
msgstr "A maximális érték nem lehet kisebb a minimális értéknél."
#: pretix/base/models/items.py
#, fuzzy
#| msgid "The maximum value must not be lower than the minimum value."
msgid "The maximum length must not be shorter than the minimum length."
msgstr "A maximális érték nem lehet kisebb a minimális értéknél."
msgstr "A maximális hossz nem lehet rövidebb a minimális hossznál."
#: pretix/base/models/items.py
msgid ""
@@ -7489,9 +7474,6 @@ msgid "The payment for this invoice has already been received."
msgstr "A számla már ki lett fizetve."
#: pretix/base/payment.py
#, fuzzy
#| msgid ""
#| "This payment is already being processed and can not be canceled any more."
msgid ""
"This payment is already being processed and cannot be canceled any more."
msgstr "Ez a fizetés már feldolgozás alatt áll, és többé nem törölhető."
@@ -8267,16 +8249,12 @@ msgid "Presale end"
msgstr "Elővétel vége"
#: pretix/base/reldate.py
#, fuzzy
#| msgid "Order email"
msgid "Order creation"
msgstr "Rendelés e-mail címe"
msgstr "Rendelés létrehozás"
#: pretix/base/reldate.py
#, fuzzy
#| msgid "Order expired"
msgid "Order expiry"
msgstr "Rendelés lejárt"
msgstr "Rendelés lejárat"
#: pretix/base/reldate.py
msgid "before"
+41 -78
View File
@@ -8,8 +8,8 @@ msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-09-30 07:26+0000\n"
"PO-Revision-Date: 2026-09-07 18:00+0000\n"
"Last-Translator: Yasunobu YesNo Kawaguchi <kawaguti@gmail.com>\n"
"PO-Revision-Date: 2026-10-05 14:00+0000\n"
"Last-Translator: Hijiri Umemoto <hijiri@umemoto.org>\n"
"Language-Team: Japanese <https://translate.pretix.eu/projects/pretix/pretix/"
"ja/>\n"
"Language: ja\n"
@@ -17,7 +17,7 @@ msgstr ""
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=1; plural=0;\n"
"X-Generator: Weblate 2026.9\n"
"X-Generator: Weblate 2026.10\n"
#: pretix/_base_settings.py
msgid "English"
@@ -1776,16 +1776,12 @@ msgid "Transmission type"
msgstr "送信タイプ"
#: pretix/base/exporters/invoices.py
#, fuzzy
#| msgid "Transmission type"
msgid "Transmission status"
msgstr "送信タイプ"
msgstr "送信ステータス"
#: pretix/base/exporters/invoices.py
#, fuzzy
#| msgid "Transmission type"
msgid "Transmission date"
msgstr "送信タイプ"
msgstr "送信日"
#: pretix/base/exporters/invoices.py
msgid "Cancellation"
@@ -4400,10 +4396,8 @@ msgid "Initialization date"
msgstr "初期化日"
#: pretix/base/models/devices.py
#, fuzzy
#| msgid "Save to profile"
msgid "Security profile"
msgstr "プロフィールに保存します"
msgstr "セキュリティ・プロフィール"
#: pretix/base/models/discount.py
msgctxt "subevent"
@@ -5779,10 +5773,8 @@ msgid "Maximum value"
msgstr "最大値"
#: pretix/base/models/items.py
#, fuzzy
#| msgid "Maximum length"
msgid "Minimum length"
msgstr "最大長"
msgstr "最小長"
#: pretix/base/models/items.py
msgid "Maximum length"
@@ -5853,10 +5845,8 @@ msgid "The maximum value must not be lower than the minimum value."
msgstr "最大値は最小値より低くできません。"
#: pretix/base/models/items.py
#, fuzzy
#| msgid "The maximum value must not be lower than the minimum value."
msgid "The maximum length must not be shorter than the minimum length."
msgstr "最大値は最小値より低くできません。"
msgstr "最大長は最小長より短くできません。"
#: pretix/base/models/items.py
msgid ""
@@ -10269,10 +10259,8 @@ msgstr ""
"す。上記で設定された\"支払いの最終日\"を過ぎてからは支払いを受け付けません。"
#: pretix/base/settings.py
#, fuzzy
#| msgid "Generate invoices for Sales channels"
msgid "Allow postponed payment choice for sales channels"
msgstr "請求書を生成する販売チャネル"
msgstr "販売チャネルの支払延期選択を許可する"
#: pretix/base/settings.py
msgid ""
@@ -10280,6 +10268,9 @@ 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 ""
"販売チャネルで支払いの延期が許可されている場合、顧客は支払い方法を選択せずに"
"注文を完了できます。これは、支払いを行う同じ人物によって注文が作成されていな"
"い場合に便利です。"
#: pretix/base/settings.py
msgid "Show start date"
@@ -16362,7 +16353,7 @@ msgstr "第三"
#: pretix/control/forms/rrule.py
msgctxt "rrule"
msgid "fourth"
msgstr ""
msgstr "4番目"
#: pretix/control/forms/rrule.py
msgctxt "rrule"
@@ -17442,28 +17433,20 @@ msgid "Queued emails have been aborted."
msgstr "キューに入っていた電子メールが、破棄されました。"
#: pretix/control/logdisplay.py
#, fuzzy
#| msgid "The property has been created."
msgid "An organizer meta property has been created."
msgstr "プロパティが作成されました。"
msgstr "主催者メタプロパティが作成されました。"
#: pretix/control/logdisplay.py
#, fuzzy
#| msgid "The selected property has been deleted."
msgid "An organizer meta property has been deleted."
msgstr "選択されたプロパティは削除されました。"
msgstr "オーガナイザーのメタプロパティが削除されました。"
#: pretix/control/logdisplay.py
#, fuzzy
#| msgid "The organizer has been changed."
msgid "An organizer meta property has been changed."
msgstr "主催者が変更されました。"
msgstr "主催者のメタプロパティが変更されました。"
#: pretix/control/logdisplay.py
#, fuzzy
#| msgid "The product has been reordered."
msgid "An organizer meta property has been reordered."
msgstr "製品の並び順が変更されました。"
msgstr "オーガナイザーのメタプロパティが再配置されました。"
#: pretix/control/logdisplay.py
msgid "Gift card acceptance for another organizer has been added."
@@ -17673,7 +17656,7 @@ msgstr "二要素の緊急コードが生成されました。"
#: pretix/control/logdisplay.py
msgid "Drift and throttle values for two-factor devices have been reset."
msgstr ""
msgstr "二要素装置のドリフト値とスロットル値がリセットされました。"
#: pretix/control/logdisplay.py
#, python-brace-format
@@ -18611,10 +18594,8 @@ msgid "Cancel"
msgstr "キャンセル"
#: pretix/control/templates/pretixcontrol/auth/oauth_authorization.html
#, fuzzy
#| msgid "Authorized apps"
msgid "Authorize"
msgstr "承認されたアプリ"
msgstr "承認する"
#: pretix/control/templates/pretixcontrol/auth/oauth_authorization.html
msgid "Error:"
@@ -21418,10 +21399,6 @@ msgstr ""
"銀行振込の参照としていくつかの場所で使用します。"
#: pretix/control/templates/pretixcontrol/events/create_basics.html
#, fuzzy
#| msgid ""
#| "We strongly recommend against using short forms of more then 16 "
#| "characters."
msgid ""
"We strongly recommend against using short forms of more than 16 characters."
msgstr "16文字を超える短縮形の使用は強くお勧めしません。"
@@ -27136,26 +27113,22 @@ msgstr "認証バックエンド"
#: pretix/control/templates/pretixcontrol/users/form.html
msgid "Reset drift and throttle"
msgstr ""
msgstr "ドリフトとスロットルをリセットする"
#: pretix/control/templates/pretixcontrol/users/form.html
#, fuzzy
#| msgid "Disable two-factor authentication"
msgid "Available two-factor authentication methods"
msgstr "二要素認証を無効にする"
msgstr "選択可能な二要素認証"
#: pretix/control/templates/pretixcontrol/users/form.html
#, fuzzy, python-format
#| msgid "Expired since %(date)s"
#, python-format
msgid "1 failed attempt since %(date)s"
msgid_plural "%(cnt)s failed attempts since %(date)s"
msgstr[0] "%(date)s以降失効"
msgstr[0] "%(date)s以降%(cnt)s回失敗"
#: pretix/control/templates/pretixcontrol/users/form.html
#, fuzzy, python-format
#| msgid "Valid until %(date)s"
#, python-format
msgid "Currently locked until %(date)s"
msgstr "%(date)sまで有効"
msgstr "現時点で%(date)sまでロックされています"
#: pretix/control/templates/pretixcontrol/users/form.html
msgid "Team memberships"
@@ -27676,18 +27649,16 @@ msgid "Invalid code, please try again."
msgstr "無効なコードです。もう一度お試しください。"
#: pretix/control/views/auth.py
#, fuzzy, python-brace-format
#| msgid "Invalid code, please try again."
#, python-brace-format
msgid "Invalid code. Please try again after waiting {value} minute."
msgid_plural "Invalid code. Please try again after waiting {value} minutes."
msgstr[0] "無効なコードです。もう一度お試しください。"
msgstr[0] "無効なコードです。{value}分後再度お試しください。"
#: pretix/control/views/auth.py
#, fuzzy, python-brace-format
#| msgid "Invalid code, please try again."
#, python-brace-format
msgid "Invalid code. Please try again after waiting {value} second."
msgid_plural "Invalid code. Please try again after waiting {value} seconds."
msgstr[0] "無効なコードです。もう一度お試しください。"
msgstr[0] "無効なコードです。{value}秒後再度お試しください。"
#: pretix/control/views/checkin.py
msgid "The selected check-ins have been reverted."
@@ -28533,10 +28504,8 @@ msgid "You entered an order in an event with a different currency."
msgstr "イベントで異なる通貨で注文を入力しました。"
#: pretix/control/views/orders.py
#, fuzzy
#| msgid "You entered an order in an event with a different currency."
msgid "You entered an order in an event that you do not have access to."
msgstr "イベントで異なる通貨で注文を入力しました。"
msgstr "アクセスできないイベントに注文が入力されました。"
#: pretix/control/views/orders.py
msgid ""
@@ -29394,10 +29363,8 @@ msgstr ""
"ください。このユーザーの過去の緊急トークンは引き続き有効です。"
#: pretix/control/views/users.py
#, fuzzy
#| msgid "The password has been reset."
msgid "The drift values for TOTP devices have been reset."
msgstr "パスワードがリセットされました。"
msgstr "TOTP デバイスのドリフト値がリセットされました。"
#: pretix/control/views/users.py
msgid "The new user has been created."
@@ -29412,14 +29379,12 @@ msgid "Bypass quota"
msgstr "クォータをバイパスする"
#: pretix/control/views/vouchers.py
#, fuzzy
#| msgid "Widget"
msgid "Budget"
msgstr "ウィジェット"
msgstr "予算"
#: pretix/control/views/vouchers.py
msgid "Budget used"
msgstr ""
msgstr "消化済み予算"
#: pretix/control/views/vouchers.py
msgid "The requested voucher does not exist."
@@ -33979,29 +33944,27 @@ msgid ""
"Not sure yet? You can complete your order first and then select a payment "
"method later."
msgstr ""
"まだ確かではありませんか?ご注文を先に完了し、その後でお支払い方法を選択でき"
"ます。"
#: pretix/presale/templates/pretixpresale/event/checkout_payment.html
msgid ""
"To do so, please first remove the payment methods you already selected above."
msgstr ""
msgstr "そのためには、まず上記で既に選択された支払い方法を削除してください。"
#: pretix/presale/templates/pretixpresale/event/checkout_payment.html
#, fuzzy, python-format
#| msgid "Your event needs to be over to use this feature."
#, python-format
msgid "Your payment needs to be completed within %(minutes)s minutes."
msgstr "この機能を使用するには、イベントが終了している必要があります。"
msgstr "支払いは、%(minutes)s分以内に完了する必要があります。"
#: pretix/presale/templates/pretixpresale/event/checkout_payment.html
#, fuzzy, python-format
#| msgid "Your event needs to be over to use this feature."
#, python-format
msgid "Your payment needs to be completed by %(deadline)s."
msgstr "この機能を使用するには、イベントが終了している必要があります。"
msgstr "支払いは、%(deadline)sまでに完了させる必要があります。"
#: pretix/presale/templates/pretixpresale/event/checkout_payment.html
#, fuzzy
#| msgid "Proceed with reset"
msgid "Proceed without selection"
msgstr "リセットを実行"
msgstr "選択なしで進む"
#: pretix/presale/templates/pretixpresale/event/checkout_questions.html
msgid "Before we continue, we need you to answer some questions."
File diff suppressed because it is too large. Load diff
+35 -55
View File
@@ -8,8 +8,9 @@ msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-09-30 07:26+0000\n"
"PO-Revision-Date: 2025-10-17 16:55+0000\n"
"Last-Translator: fd <fd@denkena-consulting.com>\n"
"PO-Revision-Date: 2026-10-02 05:00+0000\n"
"Last-Translator: Translate pretix user 594 "
"<ivagvr@users.noreply.translate.pretix.eu>\n"
"Language-Team: Russian <https://translate.pretix.eu/projects/pretix/pretix-"
"js/ru/>\n"
"Language: ru\n"
@@ -18,7 +19,7 @@ msgstr ""
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && "
"n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
"X-Generator: Weblate 5.13.3\n"
"X-Generator: Weblate 2026.10\n"
#: pretix/plugins/banktransfer/static/pretixplugins/banktransfer/ui.js
msgid "Marked as paid"
@@ -78,10 +79,8 @@ msgid "SOFORT"
msgstr ""
#: pretix/plugins/paypal2/static/pretixplugins/paypal2/pretix-paypal.js
#, fuzzy
#| msgid "Yes"
msgid "eps"
msgstr "Да"
msgstr ""
#: pretix/plugins/paypal2/static/pretixplugins/paypal2/pretix-paypal.js
msgid "MyBank"
@@ -147,7 +146,7 @@ msgstr "Подтверждается ваш платёж…"
#: pretix/plugins/paypal2/static/pretixplugins/paypal2/pretix-paypal.js
msgid "Payment method unavailable"
msgstr ""
msgstr "Способ оплаты недоступен"
#: pretix/plugins/statistics/static/pretixplugins/statistics/statistics.js
msgid "Placed orders"
@@ -200,21 +199,16 @@ msgid "Switch check-in list"
msgstr ""
#: pretix/plugins/webcheckin/static/pretixplugins/webcheckin/i18n.ts
#, fuzzy
#| msgid "Check-in QR"
msgid "Search results"
msgstr "QR-код для регистрации"
msgstr "Результаты поиска"
#: pretix/plugins/webcheckin/static/pretixplugins/webcheckin/i18n.ts
#, fuzzy
#| msgctxt "widget"
#| msgid "Close ticket shop"
msgid "No tickets found"
msgstr "Закрыть билетную кассу"
msgstr "Нет доступных билетов"
#: pretix/plugins/webcheckin/static/pretixplugins/webcheckin/i18n.ts
msgid "Result"
msgstr ""
msgstr "Результат"
#: pretix/plugins/webcheckin/static/pretixplugins/webcheckin/i18n.ts
msgid "This ticket requires special attention"
@@ -226,7 +220,7 @@ msgstr ""
#: pretix/plugins/webcheckin/static/pretixplugins/webcheckin/i18n.ts
msgid "Entry"
msgstr ""
msgstr "Вход"
#: pretix/plugins/webcheckin/static/pretixplugins/webcheckin/i18n.ts
msgid "Exit"
@@ -275,7 +269,7 @@ msgstr ""
#: pretix/plugins/webcheckin/static/pretixplugins/webcheckin/i18n.ts
msgid "Ticket not paid"
msgstr ""
msgstr "Билет не оплачен"
#: pretix/plugins/webcheckin/static/pretixplugins/webcheckin/i18n.ts
msgid "This ticket is not yet paid. Do you want to continue anyways?"
@@ -295,21 +289,19 @@ msgstr ""
#: pretix/plugins/webcheckin/static/pretixplugins/webcheckin/i18n.ts
msgid "Ticket already used"
msgstr ""
msgstr "Повторный проход по билету"
#: pretix/plugins/webcheckin/static/pretixplugins/webcheckin/i18n.ts
msgid "Information required"
msgstr ""
msgstr "Необходима информация"
#: pretix/plugins/webcheckin/static/pretixplugins/webcheckin/i18n.ts
#, fuzzy
#| msgid "Unknown error."
msgid "Unknown ticket"
msgstr "Неизвестная ошибка."
msgstr "Неизвестный билет"
#: pretix/plugins/webcheckin/static/pretixplugins/webcheckin/i18n.ts
msgid "Ticket type not allowed here"
msgstr ""
msgstr "Здесь нельзя пройти по этому билету"
#: pretix/plugins/webcheckin/static/pretixplugins/webcheckin/i18n.ts
msgid "Entry not allowed"
@@ -317,11 +309,11 @@ msgstr ""
#: pretix/plugins/webcheckin/static/pretixplugins/webcheckin/i18n.ts
msgid "Ticket code revoked/changed"
msgstr ""
msgstr "Код билета аннулирован и/или изменен"
#: pretix/plugins/webcheckin/static/pretixplugins/webcheckin/i18n.ts
msgid "Ticket blocked"
msgstr ""
msgstr "Билет заблокирован"
#: pretix/plugins/webcheckin/static/pretixplugins/webcheckin/i18n.ts
msgid "Ticket not valid at this time"
@@ -337,7 +329,7 @@ msgstr ""
#: pretix/plugins/webcheckin/static/pretixplugins/webcheckin/i18n.ts
msgid "Order not approved"
msgstr ""
msgstr "Заказ не подтвержден"
#: pretix/plugins/webcheckin/static/pretixplugins/webcheckin/i18n.ts
#, fuzzy
@@ -377,32 +369,20 @@ msgstr "Закрыть"
#: pretix/static/pretixbase/js/addressform.js
#: pretix/static/pretixpresale/js/ui/main.js
#, fuzzy
#| msgid "Cart expired"
msgid "required"
msgstr "Срок действия корзины истёк"
msgstr "обязательно"
#: pretix/static/pretixbase/js/asynctask.js
#, fuzzy
#| msgid ""
#| "Your request has been queued on the server and will now be processed. "
#| "Depending on the size of your event, this might take up to a few minutes."
msgid ""
"Your request is currently being processed. Depending on the size of your "
"event, this might take up to a few minutes."
msgstr ""
"Ваш запрос поставлен в очередь на сервере и будет обработан. В зависимости "
"от масштаба вашего мероприятия это может занять до нескольких минут."
"Ваш запрос принят в обработку. В зависимости от масштаба вашего мероприятия "
"это может занять до нескольких минут."
#: pretix/static/pretixbase/js/asynctask.js
#, fuzzy
#| msgid ""
#| "Your request has been queued on the server and will now be processed. "
#| "Depending on the size of your event, this might take up to a few minutes."
msgid "Your request has been queued on the server and will soon be processed."
msgstr ""
"Ваш запрос поставлен в очередь на сервере и будет обработан. В зависимости "
"от масштаба вашего мероприятия это может занять до нескольких минут."
msgstr "Ваш запрос поставлен в очередь на сервере и будет обработан."
#: pretix/static/pretixbase/js/asynctask.js
msgid ""
@@ -473,7 +453,7 @@ msgstr "Чтобы скопировать, нажмите Ctrl-C."
#: pretix/static/pretixcontrol/js/ui/checkinrules/App.vue
msgid "Edit"
msgstr ""
msgstr "Редактировать"
#: pretix/static/pretixcontrol/js/ui/checkinrules/App.vue
msgid "Visualize"
@@ -532,7 +512,7 @@ msgstr ""
#: pretix/static/pretixcontrol/js/ui/checkinrules/constants.ts
msgid "Duplicate"
msgstr ""
msgstr "Дубликат"
#: pretix/static/pretixcontrol/js/ui/checkinrules/constants.ts
msgctxt "entry_status"
@@ -1215,15 +1195,15 @@ msgstr ""
#: pretix/static/pretixpresale/widget/src/i18n.ts
msgid "Tuesday"
msgstr ""
msgstr "Вторник"
#: pretix/static/pretixpresale/widget/src/i18n.ts
msgid "Wednesday"
msgstr ""
msgstr "Среда"
#: pretix/static/pretixpresale/widget/src/i18n.ts
msgid "Thursday"
msgstr ""
msgstr "Четверг"
#: pretix/static/pretixpresale/widget/src/i18n.ts
msgid "Friday"
@@ -1231,11 +1211,11 @@ msgstr ""
#: pretix/static/pretixpresale/widget/src/i18n.ts
msgid "Saturday"
msgstr ""
msgstr "Суббота"
#: pretix/static/pretixpresale/widget/src/i18n.ts
msgid "Sunday"
msgstr ""
msgstr "Воскресенье"
#: pretix/static/pretixpresale/widget/src/i18n.ts
msgid "January"
@@ -1251,23 +1231,23 @@ msgstr "март"
#: pretix/static/pretixpresale/widget/src/i18n.ts
msgid "April"
msgstr "апрель"
msgstr "Апрель"
#: pretix/static/pretixpresale/widget/src/i18n.ts
msgid "May"
msgstr "май"
msgstr "Май"
#: pretix/static/pretixpresale/widget/src/i18n.ts
msgid "June"
msgstr "июнь"
msgstr "Июнь"
#: pretix/static/pretixpresale/widget/src/i18n.ts
msgid "July"
msgstr "июль"
msgstr "Июль"
#: pretix/static/pretixpresale/widget/src/i18n.ts
msgid "August"
msgstr "август"
msgstr "Август"
#: pretix/static/pretixpresale/widget/src/i18n.ts
msgid "September"
@@ -1275,7 +1255,7 @@ msgstr "сентябрь"
#: pretix/static/pretixpresale/widget/src/i18n.ts
msgid "October"
msgstr "октябрь"
msgstr "Октябрь"
#: pretix/static/pretixpresale/widget/src/i18n.ts
msgid "November"
+3 -4
View File
@@ -8,8 +8,8 @@ msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-09-30 07:26+0000\n"
"PO-Revision-Date: 2026-09-04 14:29+0000\n"
"Last-Translator: Linnea Thelander <linnea@coeo.events>\n"
"PO-Revision-Date: 2026-09-30 17:00+0000\n"
"Last-Translator: Raphael Michel <michel@rami.io>\n"
"Language-Team: Swedish <https://translate.pretix.eu/projects/pretix/pretix/"
"sv/>\n"
"Language: sv\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.9\n"
"X-Generator: Weblate 2026.9.1\n"
#: pretix/_base_settings.py
msgid "English"
@@ -19239,7 +19239,6 @@ msgstr ""
#: pretix/presale/templates/pretixpresale/event/order_pay.html
#: pretix/presale/templates/pretixpresale/event/order_pay_change.html
#: pretix/presale/templates/pretixpresale/event/position_change.html
#, fuzzy
msgid "Continue"
msgstr "Fortsätt"
+3 -4
View File
@@ -8,8 +8,8 @@ msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-09-30 07:26+0000\n"
"PO-Revision-Date: 2026-09-04 14:29+0000\n"
"Last-Translator: Linnea Thelander <linnea@coeo.events>\n"
"PO-Revision-Date: 2026-09-30 17:00+0000\n"
"Last-Translator: Raphael Michel <michel@rami.io>\n"
"Language-Team: Swedish <https://translate.pretix.eu/projects/pretix/pretix-"
"js/sv/>\n"
"Language: sv\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.9\n"
"X-Generator: Weblate 2026.9.1\n"
#: pretix/plugins/banktransfer/static/pretixplugins/banktransfer/ui.js
msgid "Marked as paid"
@@ -133,7 +133,6 @@ msgstr "Mercado Pago"
#: pretix/plugins/paypal2/static/pretixplugins/paypal2/pretix-paypal.js
#: pretix/plugins/webcheckin/static/pretixplugins/webcheckin/i18n.ts
#: pretix/static/pretixpresale/js/ui/cart.js
#, fuzzy
msgid "Continue"
msgstr "Fortsätt"
File diff suppressed because it is too large. Load diff
+6 -4
View File
@@ -8,7 +8,7 @@ msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-09-30 07:26+0000\n"
"PO-Revision-Date: 2026-09-29 09:51+0000\n"
"PO-Revision-Date: 2026-10-02 05:00+0000\n"
"Last-Translator: Nate Horst <nate@agcthailand.org>\n"
"Language-Team: Thai <https://translate.pretix.eu/projects/pretix/pretix-js/"
"th/>\n"
@@ -17,7 +17,7 @@ msgstr ""
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=1; plural=0;\n"
"X-Generator: Weblate 2026.9.1\n"
"X-Generator: Weblate 2026.10\n"
#: pretix/plugins/banktransfer/static/pretixplugins/banktransfer/ui.js
msgid "Marked as paid"
@@ -426,7 +426,7 @@ msgstr "แก้ไข"
#: pretix/static/pretixcontrol/js/ui/checkinrules/App.vue
msgid "Visualize"
msgstr ""
msgstr "แสดงภาพผัง"
#: pretix/static/pretixcontrol/js/ui/checkinrules/App.vue
msgid ""
@@ -434,10 +434,12 @@ msgid ""
"or variations are not contained in any of your rule parts so people with "
"these tickets will not get in:"
msgstr ""
"กฎของคุณมีการกรองตามสินค้าหรือรูปแบบย่อยเสมอ แต่สินค้าหรือรูปแบบย่อยต่อไปนี้ไม่ได้ถูกรวมอยู่ในส่วนใ"
"ดของกฎ คุณจึงส่งผลให้ผู้ที่ถือตั๋วเหล่านี้จะไม่สามารถผ่านเข้างานได้:"
#: pretix/static/pretixcontrol/js/ui/checkinrules/App.vue
msgid "Please double-check if this was intentional."
msgstr ""
msgstr "โปรดตรวจสอบอีกครั้งว่าเป็นการดำเนินการโดยตั้งใจหรือไม่"
#: pretix/static/pretixcontrol/js/ui/checkinrules/constants.ts
msgid "All of the conditions below (AND)"
+1 -1
View File
@@ -509,7 +509,7 @@ class BadgeExporter(BaseExporter):
('name:{}'.format(k), _('Attendee name: {part}').format(part=label))
for k, label, w in name_scheme['fields']
] if len(name_scheme['fields']) > 1 else []) + ([
('question:{}'.format(q.identifier), _('Data field: {question}').format(question=q.internal_name))
('question:{}'.format(q.identifier), _('Question: {question}').format(question=q.question))
for q in self.event.questions.filter(type__in=(
# All except TYPE_FILE and future ones
Question.TYPE_TIME, Question.TYPE_TEXT, Question.TYPE_DATE, Question.TYPE_BOOLEAN,
+2 -2
View File
@@ -382,7 +382,7 @@ class PDFCheckinList(ReportlabExportMixin, CheckInListMixin, BaseExporter):
headrowstyle = self.get_style()
headrowstyle.fontName = 'OpenSansBd'
for q in questions:
txt = str(q.internal_name)
txt = str(q.question)
p = PlainTextParagraph(txt, headrowstyle)
while p.wrap(colwidths[len(tdata[0])], 5000)[1] > 30 * mm:
txt = txt[:len(txt) - 50] + "..."
@@ -519,7 +519,7 @@ class CSVCheckinList(CheckInListMixin, ListExporter):
headers.append(_('End date'))
for q in questions:
headers.append(str(q.internal_name))
headers.append(str(q.question))
headers.append(_('Company'))
headers.append(_('Voucher code'))
+2 -2
View File
@@ -71,7 +71,7 @@ from pretix.plugins.paypal2.models import ReferencedPayPalObject
from pretix.plugins.paypal2.payment import (
PaypalMethod, PaypalMethod as Paypal, PaypalWallet,
)
from pretix.presale.views import get_cart_positions
from pretix.presale.views import get_cart
from pretix.presale.views.cart import cart_session
logger = logging.getLogger('pretix.plugins.paypal2')
@@ -130,7 +130,7 @@ class XHRView(View):
cart_total = order.pending_sum + fee
else:
cart = get_cart_positions(request)
cart = get_cart(request)
cart_payments = cart_session(request).get('payments', [])
multi_use_cart_payments = [p for p in cart_payments if p.get('multi_use_supported')]
simulated_payments = multi_use_cart_payments + [{
+11 -1
View File
@@ -161,7 +161,12 @@ class OrderMailForm(BaseMailForm):
),
label=pgettext_lazy('sendmail_form', 'Restrict to products'),
required=True,
queryset=Item.objects.none()
queryset=Item.objects.none(),
help_text=pgettext_lazy(
'sendmail_form',
'There may be multiple mails sent out to the same mail address if one order contains multiple attendee '
'products for it, if you restrict to products while also restricting mails to attendees only. '
'This is intended, as every one of those get linked to their own separate order page restricted to only that product.')
)
filter_checkins = forms.BooleanField(
label=_('Filter check-in status'),
@@ -374,6 +379,11 @@ class RuleForm(FormPlaceholderMixin, I18nModelForm):
del self.fields['subevent']
self.fields['limit_products'].queryset = Item.objects.filter(event=self.event)
self.fields['limit_products'].help_text = pgettext_lazy(
'sendmail_form',
'There may be multiple mails sent out to the same mail address if one order contains multiple attendee '
'products for it, if you restrict to products while also restricting mails to attendees only. '
'This is intended, as every one of those get linked to their own separate order page restricted to only that product.')
self.fields['schedule_type'] = forms.ChoiceField(
label=_('Type of schedule time'),
+50 -35
View File
@@ -19,6 +19,7 @@
# You should have received a copy of the GNU Affero General Public License along with this program. If not, see
# <https://www.gnu.org/licenses/>.
#
import logging
from datetime import datetime, time, timedelta
from dateutil.tz import datetime_exists
@@ -39,6 +40,8 @@ from pretix.base.models import (
)
from pretix.base.models.base import LoggingMixin
logger = logging.getLogger(__name__)
class ScheduledMail(models.Model):
STATE_SCHEDULED = 'scheduled'
@@ -115,7 +118,7 @@ class ScheduledMail(models.Model):
filter_orders_by_op = False
op_qs = OrderPosition.objects.filter(
order__event=self.event,
order__event=e,
canceled=False,
)
@@ -167,14 +170,58 @@ class ScheduledMail(models.Model):
for o in orders:
with language(o.locale, e.settings.region):
positions = list(o.positions.all())
o_sent = False
send_to_order = send_to_orders
try:
ia = o.invoice_address
except InvoiceAddress.DoesNotExist:
ia = InvoiceAddress(order=o)
if send_to_orders and o.email:
if send_to_attendees:
parent_op = None
sent_to_positions = set()
for p in positions:
if p.addon_to_id is None:
# this op might have matching add-ons, so save for later
parent_op = p
elif not parent_op or p.addon_to_id != parent_op.id:
# this op is an add-on, but not to the current parent_op
# something got mixed up as add-ons should always come directly after their parent
logger.warning(f"Add-ons are mixed up for position #{p.positionid} in order {o.full_code}")
continue
if p.id not in position_ids:
# not a matching op, just there for parent_op
continue
if p.addon_to_id and (
not p.attendee_email or p.attendee_email == parent_op.attendee_email
):
# if op is addon and either has no mail or the same as parent => send to parent
p = parent_op
if p.pk in sent_to_positions:
# this position already got an email
continue
if not p.attendee_email or p.attendee_email == o.email:
# no email or same as order => send to order
send_to_order = True
continue
email_ctx = get_email_context(
event=e,
order=o,
invoice_address=ia,
position=p,
event_or_subevent=self.subevent or e,
)
p.send_mail(self.rule.subject, self.rule.template, email_ctx,
attach_ical=self.rule.attach_ical,
log_entry_type='pretix.plugins.sendmail.rule.order.position.email.sent')
sent_to_positions.add(p.pk)
if send_to_order and o.email:
email_ctx = get_email_context(
event=e,
order=o,
@@ -184,38 +231,6 @@ class ScheduledMail(models.Model):
o.send_mail(self.rule.subject, self.rule.template, email_ctx,
attach_ical=self.rule.attach_ical,
log_entry_type='pretix.plugins.sendmail.rule.order.email.sent')
o_sent = True
if send_to_attendees:
if not self.rule.all_products:
positions = [p for p in positions if p.item_id in limit_products]
if self.subevent_id:
positions = [p for p in positions if p.subevent_id == self.subevent_id]
for p in positions:
if p.id in position_ids:
if p.attendee_email and (p.attendee_email != o.email or not o_sent):
email_ctx = get_email_context(
event=e,
order=o,
invoice_address=ia,
position=p,
event_or_subevent=self.subevent or e,
)
p.send_mail(self.rule.subject, self.rule.template, email_ctx,
attach_ical=self.rule.attach_ical,
log_entry_type='pretix.plugins.sendmail.rule.order.position.email.sent')
elif not o_sent and o.email:
email_ctx = get_email_context(
event=e,
order=o,
invoice_address=ia,
event_or_subevent=self.subevent or e,
)
o.send_mail(self.rule.subject, self.rule.template, email_ctx,
attach_ical=self.rule.attach_ical,
log_entry_type='pretix.plugins.sendmail.rule.order.email.sent')
o_sent = True
self.last_successful_order_id = o.pk
+31 -9
View File
@@ -31,6 +31,7 @@
# Unless required by applicable law or agreed to in writing, software distributed under the Apache License 2.0 is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under the License.
import logging
from datetime import datetime
from django.db.models import Exists, OuterRef, Q
@@ -43,6 +44,8 @@ from pretix.base.services.mail import mail
from pretix.base.services.tasks import ProfiledEventTask
from pretix.celery_app import app
logger = logging.getLogger(__name__)
def _chunks(lst, n):
"""
@@ -70,6 +73,8 @@ def send_mails_to_orders(event: Event, user: int, subject: dict, message: dict,
except InvoiceAddress.DoesNotExist:
ia = InvoiceAddress(order=o)
parent_op = None
sent_to_positions = set()
if recipients in ('both', 'attendees'):
for p in o.positions.annotate(
any_checkins=Exists(
@@ -85,10 +90,16 @@ def send_mails_to_orders(event: Event, user: int, subject: dict, message: dict,
)
),
).prefetch_related('addons', 'subevent'):
if p.addon_to_id is not None:
if p.addon_to_id is None:
parent_op = p
elif not parent_op or p.addon_to_id != parent_op.id:
# this op is an add-on, but not to the current parent_op
# something got mixed up as add-ons should always come directly after their parent
logger.warning(f"Add-ons are mixed up for position #{p.positionid} in order {o.full_code}")
continue
if p.item_id not in items and not any(a.item_id in items for a in p.addons.all()):
if p.item_id not in items:
continue
if filter_checkins:
@@ -99,13 +110,11 @@ def send_mails_to_orders(event: Event, user: int, subject: dict, message: dict,
if not allowed:
continue
if not p.attendee_email:
if recipients == 'attendees':
send_to_order = True
continue
if p.attendee_email == o.email and send_to_order:
continue
if p.addon_to_id and (
not p.attendee_email or p.attendee_email == parent_op.attendee_email
):
# if op is addon and either has no mail or the same as parent => send to parent
p = parent_op
if subevent and p.subevent_id != subevent:
continue
@@ -116,6 +125,18 @@ def send_mails_to_orders(event: Event, user: int, subject: dict, message: dict,
if subevents_to and p.subevent.date_from >= subevents_to:
continue
if not p.attendee_email:
send_to_order = True
continue
if p.pk in sent_to_positions:
# this position already got an email
continue
if p.attendee_email == o.email:
send_to_order = True
continue
with language(o.locale, event.settings.region):
email_context = get_email_context(event=event, order=o, invoice_address=ia, position=p)
outgoing_mail = mail(
@@ -137,6 +158,7 @@ def send_mails_to_orders(event: Event, user: int, subject: dict, message: dict,
user=user,
data=outgoing_mail.log_data(),
)
sent_to_positions.add(p.pk)
if send_to_order and o.email:
with language(o.locale, event.settings.region):
@@ -99,7 +99,7 @@ class AllTicketsPDF(BaseExporter):
('name:{}'.format(k), _('Attendee name: {part}').format(part=label))
for k, label, w in name_scheme['fields']
] if name_scheme and len(name_scheme['fields']) > 1 else []) + ([
('question:{}'.format(q.identifier), _('Data field: {question}').format(question=q.internal_name))
('question:{}'.format(q.identifier), _('Question: {question}').format(question=q.question))
for q in self.event.questions.filter(type__in=(
# All except TYPE_FILE and future ones
Question.TYPE_TIME, Question.TYPE_TEXT, Question.TYPE_DATE, Question.TYPE_BOOLEAN,
@@ -1,5 +1,4 @@
import type { SubEvent } from './i18n'
import type { LocalizableString } from '@/pretix/static/pretixbase/js/i18n'
import type { I18nString, SubEvent } from './i18n'
const settingsEl = document.getElementById('api-settings')
const { urls } = JSON.parse(settingsEl.textContent || '{}') as { urls: {
@@ -60,8 +59,8 @@ export interface Position {
order: string
positionid: number
canceled?: boolean
item: { id?: number; name: LocalizableString; internal_name?: string; admission?: boolean }
variation: { id?: number; value: LocalizableString } | null
item: { id?: number; name: I18nString; internal_name?: string; admission?: boolean }
variation: { id?: number; value: I18nString } | null
price: string
attendee_name: string
attendee_name_parts: Record<string, string>
@@ -111,8 +110,8 @@ export interface Answer {
export interface AnswerQuestion {
id: number
question: LocalizableString
help_text?: LocalizableString
question: I18nString
help_text?: I18nString
type: string
required: boolean
position: number
@@ -139,12 +138,12 @@ export interface QuestionOption {
id: number
identifier: string
position: number
answer: LocalizableString
answer: I18nString
}
export interface Addon {
item: { name: LocalizableString; internal_name?: string }
variation: { value: LocalizableString } | null
item: { name: I18nString; internal_name?: string }
variation: { value: I18nString } | null
}
export interface CheckinStatusVariation {
@@ -2,8 +2,7 @@
import { ref, computed, nextTick, onMounted, onUnmounted } from 'vue'
import { api } from '../api'
import type { CheckinList, Position, RedeemResponse, CheckinStatus, AnswerQuestion } from '../api'
import { STRINGS, formatSubevent, formatAnswer } from '../i18n'
import { localize_string } from '@/pretix/static/pretixbase/js/i18n'
import { STRINGS, i18nstringLocalize, formatSubevent, formatAnswer } from '../i18n'
import CheckinlistSelect from './checkinlist-select.vue'
import SearchresultItem from './searchresult-item.vue'
@@ -115,9 +114,9 @@ const checkResultAddons = computed(() => {
if (!checkResult.value?.position?.addons) return ''
return checkResult.value.position.addons.map((addon) => {
if (addon.variation) {
return `+ ${addon.item.internal_name || localize_string(addon.item.name)} – ${localize_string(addon.variation.value)}`
return `+ ${addon.item.internal_name || i18nstringLocalize(addon.item.name)} – ${i18nstringLocalize(addon.variation.value)}`
}
return '+ ' + (addon.item.internal_name || localize_string(addon.item.name))
return '+ ' + (addon.item.internal_name || i18nstringLocalize(addon.item.name))
}).join('\n')
})
@@ -126,9 +125,9 @@ const checkResultSubevent = computed(() => formatSubevent(checkResult.value?.pos
const checkResultItemvar = computed(() => {
if (!checkResult.value?.position) return ''
if (checkResult.value.position.variation) {
return `${localize_string(checkResult.value.position.item.name)} – ${localize_string(checkResult.value.position.variation.value)}`
return `${i18nstringLocalize(checkResult.value.position.item.name)} – ${i18nstringLocalize(checkResult.value.position.variation.value)}`
}
return localize_string(checkResult.value.position.item.name)
return i18nstringLocalize(checkResult.value.position.item.name)
})
const checkResultText = computed(() => {
@@ -317,9 +316,9 @@ async function check (
if (!answers.value[q.id.toString()]) {
answers.value[q.id.toString()] = ''
}
;(q as AnswerQuestion).question = localize_string(q.question)
;(q as AnswerQuestion).question = i18nstringLocalize(q.question)
for (const o of q.options) {
;(o as { answer: string }).answer = localize_string(o.answer)
;(o as { answer: string }).answer = i18nstringLocalize(o.answer)
}
}
nextTick(() => {
@@ -411,7 +410,7 @@ onUnmounted(() => {
span(v-for="a in checkResult.position.answers")
span(v-if="a.question.show_during_checkin")
br
strong {{ localize_string(a.question.question) }}:
strong {{ i18nstringLocalize(a.question.question) }}:
| {{ formatAnswer(a.answer, a.question) }}
strong(v-for="t in checkResult.checkin_texts")
br
@@ -1,8 +1,7 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import type { Position } from '../api'
import { STRINGS, formatSubevent } from '../i18n'
import { localize_string } from '@/pretix/static/pretixbase/js/i18n'
import { STRINGS, i18nstringLocalize, formatSubevent } from '../i18n'
const props = defineProps<{
position: Position
@@ -23,9 +22,9 @@ const status = computed(() => {
const itemvar = computed(() => {
if (props.position.variation) {
return `${localize_string(props.position.item.name)} – ${localize_string(props.position.variation.value)}`
return `${i18nstringLocalize(props.position.item.name)} – ${i18nstringLocalize(props.position.variation.value)}`
}
return localize_string(props.position.item.name)
return i18nstringLocalize(props.position.item.name)
})
const subevent = computed(() => formatSubevent(props.position.subevent))
@@ -1,5 +1,3 @@
import { localize_string } from '@/pretix/static/pretixbase/js/i18n'
const body = document.body
export const timezone = body.dataset.timezone ?? 'UTC'
@@ -11,6 +9,27 @@ export const pretixLocale = body.dataset.pretixlocale ?? 'en'
moment.locale(datetimeLocale)
export function gettext (msgid: string): string {
if (typeof django !== 'undefined' && typeof django.gettext !== 'undefined') {
return django.gettext(msgid)
}
return msgid
}
export function ngettext (singular: string, plural: string, count: number): string {
if (typeof django !== 'undefined' && typeof django.ngettext !== 'undefined') {
return django.ngettext(singular, plural, count)
}
return plural
}
export type I18nString = string | Record<string, string> | null | undefined
export function i18nstringLocalize (obj: I18nString): string {
// external
return i18nstring_localize(obj)
}
export const STRINGS: Record<string, string> = {
'checkinlist.select': gettext('Select a check-in list'),
'checkinlist.none': gettext('No active check-in lists found.'),
@@ -64,7 +83,7 @@ export interface SubEvent {
export function formatSubevent (subevent: SubEvent | null | undefined): string {
if (!subevent) return ''
const name = localize_string(subevent.name)
const name = i18nstringLocalize(subevent.name)
const date = moment.utc(subevent.date_from).tz(timezone).format(datetimeFormat)
return `${name} · ${date}`
}
@@ -26,6 +26,7 @@
data-pretixlocale="{{ request.LANGUAGE_CODE }}" data-timezone="{{ request.event.settings.timezone }}">
<div id="app" data-event-name="{{ request.event.name }}"></div>
{% compress js %}
<script type="text/javascript" src="{% static "pretixbase/js/i18nstring.js" %}"></script>
<script type="text/javascript" src="{% static "moment/moment-with-locales.js" %}"></script>
<script type="text/javascript" src="{% static "moment/moment-timezone-with-data-1970-2030.js" %}"></script>
<script type="text/javascript" src="{% static "jquery/js/jquery-3.6.4.min.js" %}"></script>
@@ -36,7 +37,7 @@
{
"urls": {
"lists": "{% url "api-v1:checkinlist-list" event=request.event.slug organizer=request.organizer.slug %}",
"questions": "{% url "api-v1:positiondatafield-list" event=request.event.slug organizer=request.organizer.slug %}"
"questions": "{% url "api-v1:question-list" event=request.event.slug organizer=request.organizer.slug %}"
}
}
</script>
+57 -17
View File
@@ -63,7 +63,7 @@ from django_scopes import scopes_disabled
from pretix.base.models import Customer, Membership, Order
from pretix.base.models.items import Question
from pretix.base.models.orders import (
InvoiceAddress, OrderPayment, QuestionAnswer, QuestionnaireRenderer,
InvoiceAddress, OrderPayment, QuestionAnswer,
)
from pretix.base.models.tax import TaxedPrice, TaxRule
from pretix.base.services.cart import (
@@ -98,9 +98,7 @@ from pretix.presale.signals import (
question_form_fields_overrides,
)
from pretix.presale.utils import customer_login
from pretix.presale.views import (
CartMixin, get_cart_is_free, get_cart_positions,
)
from pretix.presale.views import CartMixin, get_cart, get_cart_is_free
from pretix.presale.views.cart import (
_items_from_post_data, cart_session, create_empty_cart_id,
get_or_create_cart_id,
@@ -499,7 +497,7 @@ class AddOnsStep(CartMixin, AsyncAction, TemplateFlowStep):
self.request = request
# check whether addons are applicable
if get_cart_positions(request).filter(item__addons__isnull=False).exists():
if get_cart(request).filter(item__addons__isnull=False).exists():
return True
# don't re-check whether cross-selling is applicable if we're already past the AddOnsStep
@@ -525,7 +523,7 @@ class AddOnsStep(CartMixin, AsyncAction, TemplateFlowStep):
def is_completed(self, request, warn=False):
if getattr(self, '_completed', None) is not None:
return self._completed
for cartpos in get_cart_positions(request).filter(addon_to__isnull=True).prefetch_related(
for cartpos in get_cart(request).filter(addon_to__isnull=True).prefetch_related(
'item__addons', 'item__addons__addon_category', 'addons', 'addons__item'
):
a = cartpos.addons.all()
@@ -588,7 +586,7 @@ class AddOnsStep(CartMixin, AsyncAction, TemplateFlowStep):
formset = []
quota_cache = {}
item_cache = {}
for cartpos in sorted(get_cart_positions(self.request).filter(addon_to__isnull=True).prefetch_related(
for cartpos in sorted(get_cart(self.request).filter(addon_to__isnull=True).prefetch_related(
'item__addons', 'item__addons__addon_category', 'addons', 'addons__variation',
), key=lambda c: c.sort_key):
formsetentry = {
@@ -1092,17 +1090,59 @@ class QuestionsStep(CartQuestionsViewMixin, CartMixin, TemplateFlowStep):
return False
for cp in self._positions_for_questions:
renderer = cp.rendered_questions
answ = {
aw.question_id: aw for aw in cp.answerlist
}
question_cache = {
q.pk: q for q in cp.item.questions_to_ask
}
def question_is_visible(parentid, qvals):
if parentid not in question_cache:
return False
parentq = question_cache[parentid]
if parentq.dependency_question_id and not question_is_visible(parentq.dependency_question_id, parentq.dependency_values):
return False
if parentid not in answ:
return False
return (
('True' in qvals and answ[parentid].answer == 'True')
or ('False' in qvals and answ[parentid].answer == 'False')
or (any(qval in [o.identifier for o in answ[parentid].options.all()] for qval in qvals))
)
def question_is_required(q):
return (
q.required and
(not q.dependency_question_id or question_is_visible(q.dependency_question_id, q.dependency_values))
)
if not self.all_optional:
for qc in renderer.qrows:
if qc.user_datafield_id and renderer.row_is_required(qc) and qc.user_datafield_id not in renderer.answer_cache:
if warn:
messages.warning(request, _('Please fill in answers to all required questions.'))
return False
if qc.system_datafield and renderer.row_is_required(qc) and not renderer.get_system_answer(qc.system_datafield):
for q in cp.item.questions_to_ask:
if question_is_required(q) and q.id not in answ:
if warn:
messages.warning(request, _('Please fill in answers to all required questions.'))
return False
if cp.item.ask_attendee_data and self.request.event.settings.get('attendee_names_required', as_type=bool) \
and not cp.attendee_name_parts:
if warn:
messages.warning(request, _('Please fill in answers to all required questions.'))
return False
if cp.item.ask_attendee_data and self.request.event.settings.get('attendee_emails_required', as_type=bool) \
and cp.attendee_email is None:
if warn:
messages.warning(request, _('Please fill in answers to all required questions.'))
return False
if cp.item.ask_attendee_data and self.request.event.settings.get('attendee_company_required', as_type=bool) \
and cp.company is None:
if warn:
messages.warning(request, _('Please fill in answers to all required questions.'))
return False
if cp.item.ask_attendee_data and self.request.event.settings.get('attendee_addresses_required', as_type=bool) \
and (cp.street is None and cp.city is None and cp.country is None):
if warn:
messages.warning(request, _('Please fill in answers to all required questions.'))
return False
responses = question_form_fields.send(sender=self.request.event, position=cp)
form_data = cp.meta_info_data.get('question_form_data', {})
@@ -1270,7 +1310,7 @@ class PaymentStep(CartMixin, TemplateFlowStep):
@cached_property
def _total_order_value(self):
cart = get_cart_positions(self.request)
cart = get_cart(self.request)
try:
fees = get_fees(
event=self.request.event, request=self.request, invoice_address=self.invoice_address,
@@ -1462,7 +1502,7 @@ class PaymentStep(CartMixin, TemplateFlowStep):
messages.error(request, _('Please select a payment method to proceed.'))
return False
cart = get_cart_positions(self.request)
cart = get_cart(self.request)
try:
fees = get_fees(
event=self.request.event,
@@ -1502,7 +1542,7 @@ class PaymentStep(CartMixin, TemplateFlowStep):
def is_applicable(self, request):
self.request = request
for cartpos in get_cart_positions(self.request):
for cartpos in get_cart(self.request):
if cartpos.requires_approval(invoice_address=self.invoice_address):
if 'payments' in self.cart_session:
del self.cart_session['payments']
+2 -2
View File
@@ -148,8 +148,8 @@ class CheckoutFieldRenderer(FieldRenderer):
label_for = self.field.id_for_label
label_id = ""
if hasattr(self.field.field, 'datafield') and self.field.field.datafield.identifier:
attrs["data-identifier"] = self.field.field.datafield.identifier
if hasattr(self.field.field, 'question') and self.field.field.question.identifier:
attrs["data-identifier"] = self.field.field.question.identifier
html = render_label(
label,
@@ -175,7 +175,7 @@
<div class="panel-body">
<dl class="dl-horizontal">
{% for ans in checkout_session.answers.all %}
<dt>{{ ans.question.internal_name }}</dt> TODO(questionnaires) - nicht internal_name, sondern QuestionnaireRow.label
<dt>{{ ans.question.question }}</dt>
<dd>{% include "pretixpresale/event/fragment_question_answer.html" with request=request question=ans.question answer=ans %}</dd>
{% endfor %}
</dl>
@@ -93,6 +93,9 @@
</summary>
<div>
<div class="panel-body questions-form" data-address-information-url="{% url "js_helpers.address_form" %}">
{% if event.settings.attendee_data_explanation_text and pos.item.ask_attendee_data %}
{{ event.settings.attendee_data_explanation_text|rich_text }}
{% endif %}
{% if forloop.counter > 1 and event.settings.checkout_show_copy_answers_button %}
<div class="form-group">
<div class="col-md-9 col-md-offset-3">
@@ -156,8 +156,55 @@
{% endif %}
{% if line.has_questions %}
<dl class="dl-indented">
{% for q in line.rendered_questions %}
<dt>{{ q.label }}</dt>
{% if line.item.ask_attendee_data %}
{% if event.settings.attendee_names_asked %}
<dt class="sr-only">
{% trans "Attendee name" %}
</dt>
<dd class="toplevel{% if event.settings.attendee_addresses_asked and not event.settings.attendee_emails_asked %} blank-after{% endif %}">
<span data-toggle="tooltip" title="{% trans "Attendee name" %}">
{% if line.attendee_name %}{{ line.attendee_name }}{% else %}<em class="text-muted">{% trans "No attendee name provided" %}</em>{% endif %}
</span>
</dd>
{% endif %}
{% if event.settings.attendee_emails_asked and line.attendee_email %}
<dt class="sr-only">
{% trans "Attendee email" %}
</dt>
<dd class="toplevel{% if event.settings.attendee_addresses_asked %} blank-after{% endif %}">
<span data-toggle="tooltip" title="{% trans "Attendee email" %}">
{{ line.attendee_email }}
</span>
</dd>
{% endif %}
{% if event.settings.attendee_company_asked and line.company %}
<dt class="sr-only">
{% trans "Attendee company" %}
</dt>
<dd class="toplevel">
<span data-toggle="tooltip" title="{% trans "Attendee company" %}">
{{ line.company }}
</span>
</dd>
{% endif %}
{% if event.settings.attendee_addresses_asked %}
{% if line.street or line.zipcode or line.city %}
<dt class="sr-only">
{% trans "Attendee address" %}
</dt>
<dd class="toplevel">
<span data-toggle="tooltip" title="{% trans "Attendee address" %}">
{{ line.street|default_if_none:""|linebreaksbr }}<br>
{{ line.zipcode|default_if_none:"" }} {{ line.city|default_if_none:"" }}<br>
{% if line.state %}{{ line.state_for_address }}<br>{% endif %}
{{ line.country.name|default_if_none:"" }}
</span>
</dd>
{% endif %}
{% endif %}
{% endif %}
{% for q in line.questions %}
<dt>{{ q.question }}</dt>
<dd>
{% include "pretixpresale/event/fragment_question_answer.html" with request=request question=q answer=q.answer %}
</dd>
@@ -1,8 +1,7 @@
{% load safelink %}
{% load i18n %}
{% load rich_text %}
{% if not answer and not question %}
{% elif answer %}
{% if answer %}
{% if answer.file %}
<span class="fa fa-file" aria-hidden="true"></span>
<a href="{{ answer.frontend_file_url }}?token={% answer_token request answer %}">
@@ -347,12 +347,12 @@
{% endif %}
</dl>
{% if order.rendered_questions %}
{% if order.answers.all %}
<hr>
<dl class="dl-horizontal">
{% for q in order.rendered_questions %}
<dt>{{ q.label }}</dt>
<dd>{% include "pretixpresale/event/fragment_question_answer.html" with request=request question=q answer=q.answer %}</dd>
{% for ans in order.answers.all %}
<dt>{{ ans.question.question }}</dt>
<dd>{% include "pretixpresale/event/fragment_question_answer.html" with request=request question=ans.question answer=ans %}</dd>
{% endfor %}
</dl>
{% endif %}
Loaded 100 of 167 files, more files were not shown because too many files have changed in this diff. Show more