Compare commits

...

231 Commits

Author SHA1 Message Date
Raphael Michel
2269c8dee0 Bump version to 3.6.0 2020-02-17 16:38:53 +01:00
Raphael Michel
46295ea887 Merge pull request #1581 from pretix-translations/weblate-pretix-pretix
Translations update from Weblate
2020-02-17 16:31:00 +01:00
Raphael Michel
e41863229b Translated on translate.pretix.eu (German (informal))
Currently translated at 100.0% (3474 of 3474 strings)

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

powered by weblate
2020-02-17 16:30:22 +01:00
Raphael Michel
ca5a6ddba1 Translated on translate.pretix.eu (German)
Currently translated at 100.0% (3474 of 3474 strings)

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

powered by weblate
2020-02-17 16:30:21 +01:00
Raphael Michel
4d4dafb5dd Update po files
[CI skip]

Signed-off-by: Raphael Michel <mail@raphaelmichel.de>
2020-02-17 16:22:55 +01:00
Raphael Michel
9c2af952b7 Fix another empty sequence error 2020-02-17 14:00:15 +01:00
Raphael Michel
dc6e425c2a Fix accidental string interpolation in a test case 2020-02-17 13:57:36 +01:00
Raphael Michel
5f65b9528f Fix a migration exception 2020-02-17 13:30:19 +01:00
Raphael Michel
8957c2f106 Seating: Support custom row and seat labels 2020-02-17 13:15:49 +01:00
Raphael Michel
2bbbc88a9c Allow duplicate ticket secrets in different organizers 2020-02-17 12:35:02 +01:00
Raphael Michel
162b7c1b52 Fixed subsequent issue with failed paypal payments 2020-02-14 14:22:05 +01:00
Raphael Michel
755f3d53b6 Fix issue with failed paypal payments 2020-02-14 13:24:18 +01:00
Raphael Michel
f6db62d6ce Add retry button to cookie failure page 2020-02-14 11:43:14 +01:00
Raphael Michel
aa1ffc402c Remove some unnecessary queries 2020-02-14 11:25:28 +01:00
Raphael Michel
2c9b96f0c5 Fix various issues with min() statements 2020-02-14 09:16:04 +01:00
Raphael Michel
16599e242d Partially revert last change 2020-02-13 17:39:17 +01:00
Raphael Michel
19c13d7f38 Improved order position secret generation 2020-02-13 17:04:50 +01:00
Raphael Michel
65db8cd583 Widget: Pass referer to cart session 2020-02-13 09:58:08 +01:00
Raphael Michel
d0794d7b94 Optionally allow to automatically reissue an invoice after a data change 2020-02-13 09:49:21 +01:00
Raphael Michel
a770f5a8e7 Add FAQ section on payment deadlines 2020-02-13 09:37:25 +01:00
Raphael Michel
80a3063799 Fix KeyError in sendmail history 2020-02-13 09:22:50 +01:00
Raphael Michel
34ec11ecfa Fix KeyError for form validation 2020-02-13 09:21:23 +01:00
Martin Gross
a1da2eafdc Reinstate MOTO-Flagging for Reseller Scheme-TX (#1570) 2020-02-12 09:49:33 +01:00
Raphael Michel
6bc2175ea9 More robust redis connections 2020-02-12 09:29:30 +01:00
Raphael Michel
21dcb4f43d Revert "Optional MOTO-Flagging for Reseller Scheme-TXs (#1570)"
This reverts commit 0a920ac21c.
2020-02-12 08:01:24 +01:00
Raphael Michel
e9722bcdbd Merge pull request #1578 from pretix-translations/weblate-pretix-pretix
Translations update from Weblate
2020-02-11 17:22:04 +01:00
Raphael Michel
e7eb8e3111 Translated on translate.pretix.eu (German (informal))
Currently translated at 100.0% (3472 of 3472 strings)

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

powered by weblate
2020-02-11 17:21:00 +01:00
Raphael Michel
a895d83764 Translated on translate.pretix.eu (German)
Currently translated at 100.0% (3472 of 3472 strings)

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

powered by weblate
2020-02-11 17:20:59 +01:00
Raphael Michel
b6697b838b Update po files
[CI skip]

Signed-off-by: Raphael Michel <mail@raphaelmichel.de>
2020-02-11 16:55:36 +01:00
Raphael Michel
0d8c4271a9 Show successful payments on the invoice 2020-02-11 16:54:02 +01:00
Raphael Michel
d226bbda5c Order data export: Add column with the number of positions 2020-02-11 16:25:48 +01:00
Raphael Michel
38d0198dea Do not show a flag for single language events 2020-02-11 13:19:46 +01:00
Martin Gross
0a920ac21c Optional MOTO-Flagging for Reseller Scheme-TXs (#1570)
* Optional MOTO-Flagging for Reseller Scheme-TXs

* Update src/pretix/plugins/stripe/payment.py

Co-Authored-By: Raphael Michel <michel@rami.io>

* Update src/pretix/plugins/stripe/payment.py

Co-Authored-By: Raphael Michel <michel@rami.io>

* Manually rebase again...

* Fix a single whitespace for style...

Co-authored-by: Raphael Michel <mail@raphaelmichel.de>
2020-02-11 11:08:28 +01:00
Raphael Michel
7acee9458d Move bulk_create logic during bulk voucher creation 2020-02-09 12:17:48 +01:00
Raphael Michel
82e40ce664 Merge pull request #1574 from pretix-translations/weblate-pretix-pretix
Translations update from Weblate
2020-02-08 13:45:16 +01:00
Raphael Michel
4632269ac3 Translated on translate.pretix.eu (German (informal))
Currently translated at 100.0% (3463 of 3463 strings)

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

powered by weblate
2020-02-08 13:44:32 +01:00
Raphael Michel
6d7e1ef53d Translated on translate.pretix.eu (German)
Currently translated at 100.0% (3463 of 3463 strings)

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

powered by weblate
2020-02-08 13:44:30 +01:00
Raphael Michel
3ea4cdc3b3 Small categorization adjustments 2020-02-08 13:14:19 +01:00
Raphael Michel
e4619eeca3 Update po files
[CI skip]

Signed-off-by: Raphael Michel <mail@raphaelmichel.de>
2020-02-08 12:42:35 +01:00
Raphael Michel
bb5c7c5ad7 Re-introduce plugin categories 2020-02-08 12:38:43 +01:00
Raphael Michel
9984fe97ba Add OrderPayment.fail() to prevent race conditions (#1572) 2020-02-07 09:00:35 +01:00
Martin Gross
242dd24caa Fix hiding of payment methods 2020-02-06 10:53:02 +01:00
Raphael Michel
2482d9390a Fix incorrect settings field type 2020-02-05 21:29:22 +01:00
Raphael Michel
3b4923ccae Fix required field 2020-02-05 18:34:58 +01:00
Raphael Michel
8a2e4385ff Fix required field 2020-02-05 18:33:40 +01:00
Raphael Michel
e83b8ac218 Allow to hide payment methods behind a secret link 2020-02-05 18:09:27 +01:00
Raphael Michel
b387fba5f4 Hide time on list of events for event series 2020-02-05 17:30:15 +01:00
Raphael Michel
da68cb618e Improved logging and transaction handling around payment confirmations 2020-02-05 12:02:02 +01:00
Raphael Michel
eb11dac21e Fix single badge downloads 2020-02-05 10:31:11 +01:00
Raphael Michel
6e531ee067 Event list filters: Deal with events without presale start/end 2020-02-05 10:31:11 +01:00
Raphael Michel
c8e6daa7a1 Do not show disabled sub-methods in timeline 2020-02-05 10:31:11 +01:00
Martin Gross
b3e3d427cb Add more Stripe Payment Methods, simplify forms (#1571)
* Add more Stripe Payment Methods, simplify forms

* Revert accidential commit of boxoffice control renderer...

* Use existing QR-Code encoding in presale
2020-02-05 09:50:29 +01:00
pajowu
6e88054af7 Send signal on checkin (#1546)
* Send signal when orderposition is checked in

* Add position_checked_in signal to documentation

* Rename signal to checkin_created

* Update general.rst

* Update signals.py

Co-authored-by: Raphael Michel <mail@raphaelmichel.de>
2020-02-04 18:26:35 +01:00
Raphael Michel
22dfa0e61d Use select2 input for category fields 2020-02-04 18:22:03 +01:00
Alexander Schwartz
833cd32578 Comparison for file extensions should be case insensitive (#1563) 2020-02-04 17:09:12 +01:00
Raphael Michel
fd1c964c92 Fix #1378 -- API: Allow to access and modify (some) event setti… (#1569)
* API: Allow to access event settings

* Convert most "general" settings

* Smaller fixes

* Add more settings

* Relative dates, nulling

* Fix a test failure

* Fix wrong attribute access
2020-02-04 17:06:23 +01:00
Raphael Michel
87b10ef055 Allow to print multiple badges on one page (#1380)
* Allow to print multiple badges on one page

* Fix test

* Add more sizes

* Add A4 sizes
2020-02-04 17:02:33 +01:00
Raphael Michel
734f65b10b Ask Google not to index the "Resend order links" site 2020-02-04 16:26:05 +01:00
Martin Gross
0f826a6f76 Show payment card information for Stripe PaymentIntents 2020-02-04 15:09:34 +01:00
Raphael Michel
35e521cc55 Merge pull request #1564 from pretix-translations/weblate-pretix-pretix
Update from Weblate
2020-02-03 17:58:29 +01:00
Martin Gross
63c845574f Translated on translate.pretix.eu (German)
Currently translated at 100.0% (3363 of 3363 strings)

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

powered by weblate
2020-02-03 15:39:33 +01:00
Raphael Michel
5a675cc75d Translated on translate.pretix.eu (German)
Currently translated at 100.0% (3363 of 3363 strings)

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

powered by weblate
2020-02-03 15:39:33 +01:00
András Veres-Szentkirályi
994dc9bf76 Translated on translate.pretix.eu (Hungarian)
Currently translated at 2.8% (94 of 3363 strings)

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

powered by weblate
2020-02-03 15:39:33 +01:00
Raphael Michel
cc4a07e3b0 Translated on translate.pretix.eu (German (informal))
Currently translated at 100.0% (3363 of 3363 strings)

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

powered by weblate
2020-02-03 15:39:33 +01:00
Raphael Michel
2ca88d5328 Translated on translate.pretix.eu (German)
Currently translated at 100.0% (3363 of 3363 strings)

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

powered by weblate
2020-02-03 15:39:33 +01:00
Raphael Michel
0bca9b9bf1 Box office: Support for Stripe Terminal 2020-02-03 15:39:19 +01:00
Raphael Michel
742d2f11be SCSS: Fix font generation error 2020-02-01 16:25:05 +01:00
Raphael Michel
5ea5b82994 Docs: Fix typo 2020-02-01 16:25:00 +01:00
Raphael Michel
81245cf125 Fix #1549 -- JS API to open pretix Button 2020-02-01 15:59:24 +01:00
Raphael Michel
c6bcd05404 Widget: Fix button behaviour without iframe 2020-02-01 15:39:03 +01:00
Raphael Michel
1999a25095 Widget: no reload on buttons 2020-02-01 14:19:39 +01:00
Raphael Michel
62f7c5ba0f Doc spelling: Add SQL to wordlist 2020-02-01 14:08:24 +01:00
Raphael Michel
d11b0e92f1 Reverse default order of subevents 2020-02-01 13:59:55 +01:00
Raphael Michel
662bdea45b Preload all samples 2020-02-01 13:48:56 +01:00
Raphael Michel
d37cc4f641 Font API: Support for script-specific samples 2020-02-01 13:46:50 +01:00
Raphael Michel
6b2bc71be9 Order list export: consistent decimals 2020-02-01 13:06:40 +01:00
Raphael Michel
f267940562 Update Sphinx 2020-02-01 12:57:19 +01:00
Raphael Michel
7140406f35 Order data export: Split multiple choice questions in multiple columns 2020-02-01 12:47:39 +01:00
Raphael Michel
e275e2e240 API: Add endpoint to expose pretix version 2020-01-31 11:11:24 +01:00
Raphael Michel
75c0920f5e API: Allow to mark order as pending when creating refunds 2020-01-31 10:48:32 +01:00
Raphael Michel
b6efe9ae1e Fix middleware name 2020-01-29 12:44:39 +01:00
Raphael Michel
a28378bac9 Fix further problems with middleware ordering 2020-01-29 11:50:09 +01:00
Raphael Michel
a940fa9eb7 Correct order of middlewares, thereby fix event list widget on custom domains
With the incorrect order, Django used the wrong URL config file to
determine whether this URL is valid and APPEND_SLASH kicked in too
often.
2020-01-28 23:38:09 +01:00
Raphael Michel
332fba6168 DOwngrade libsass 2020-01-28 22:46:43 +01:00
Raphael Michel
41655532e9 Upgrade bootstrap to 3.4.0 2020-01-28 22:46:43 +01:00
Martin Gross
6cc9801fe1 Only allow letters, numbers, dots and dashes for giftcard codes 2020-01-28 16:53:44 +01:00
Raphael Michel
29ff5b9416 Use correct timezone for events in event list view 2020-01-28 13:32:43 +01:00
Raphael Michel
889dd651ef Add BasePaymentProvider.matching_id() 2020-01-27 21:46:36 +01:00
Raphael Michel
8c7d7a3055 Add documentation on the campaign module api 2020-01-27 21:24:48 +01:00
Raphael Michel
ff67931c04 Fix a documentation error 2020-01-27 16:51:50 +01:00
Raphael Michel
faa6f0e0a3 Correctly copy seats when copying events 2020-01-27 10:52:25 +01:00
Raphael Michel
68ec37605f Fix another doc typo 2020-01-26 19:35:58 +01:00
Raphael Michel
2ef8b89da0 Add reseller to doc wordlist 2020-01-25 17:16:09 +01:00
Raphael Michel
dfc746ea7a Add documentation on VAR API 2020-01-25 15:26:32 +01:00
Raphael Michel
661546f130 Update from Weblate (#1560)
Update from Weblate
2020-01-25 15:23:29 +01:00
Raphael Michel
5e61342ff5 Add an API for teams (#1562)
* Add Team resource to API

* Add team memer endpoints

* Add team invites endpoint

* Add token endpoints
2020-01-25 15:22:50 +01:00
Prokaj Miklós
4eadfdeec2 Translated on translate.pretix.eu (Hungarian)
Currently translated at 100.0% (103 of 103 strings)

Translation: pretix/pretix (frontend)
Translate-URL: https://translate.pretix.eu/projects/pretix/pretix-js/hu/

powered by weblate
2020-01-25 10:07:47 +00:00
Prokaj Miklós
8284a9de44 Translated on translate.pretix.eu (Hungarian)
Currently translated at 1.0% (35 of 3363 strings)

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

powered by weblate
2020-01-25 10:07:47 +00:00
Prokaj Miklós
ae2e70245f Added translation on translate.pretix.eu (Hungarian) 2020-01-25 10:07:47 +00:00
Prokaj Miklós
a92e283a66 Added translation on translate.pretix.eu (Hungarian) 2020-01-25 10:07:47 +00:00
Mie Frydensbjerg
9e2c0d8152 Translated on translate.pretix.eu (Danish)
Currently translated at 47.7% (1603 of 3360 strings)

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

powered by weblate
2020-01-25 10:07:47 +00:00
Raphael Michel
57453a5b00 Fix missing known_errortypes attribute 2020-01-25 11:07:42 +01:00
gnomus
1ccf677ea2 Solve some Docker Setup scaling issues (#1561) 2020-01-24 14:14:36 +01:00
Raphael Michel
0a9daf0d3a API: Fix crash when passing an empty seat_category_mapping during event creation 2020-01-23 14:27:43 +01:00
Raphael Michel
934217ee4f Attach invoices to order changed/canceled emails 2020-01-23 14:25:20 +01:00
Raphael Michel
deff282a63 Do not allow slugs to start with a non-alphanumeric character 2020-01-23 09:39:39 +01:00
Raphael Michel
bcd687764c API: Allow to create payments directly 2020-01-22 17:15:40 +01:00
Raphael Michel
8d7224fecc Force-escape all PDF values on the renderer level (#1556)
* Force-escape all PDF values

* Do not concatenate empty strings to name combinations
2020-01-22 14:56:25 +01:00
Martin Gross
3fff3378c0 Handle media_url of embedded images in simple mail renderer better for instances with dedicated media-hosts 2020-01-21 10:36:46 +01:00
Raphael Michel
91ae89d463 Add cache to sass compiler 2020-01-20 12:04:58 +01:00
Martin Gross
5c0d112def Add simple e-mail-renderer with logo (#1552)
* Add unembellished eMail-renderer

* Fix layout issues with very wide images

* Use prettier padding

* Rename to "simple with logo"

Co-authored-by: Raphael Michel <mail@raphaelmichel.de>
2020-01-20 11:26:53 +01:00
Raphael Michel
f7ae90811e Merge pull request #1548 from pretix-translations/weblate-pretix-pretix
Update from Weblate
2020-01-20 10:50:34 +01:00
Luka
6ec8c33ecc Translated on translate.pretix.eu (Slovenian)
Currently translated at 20.8% (698 of 3360 strings)

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

powered by weblate
2020-01-20 08:46:31 +00:00
Mie Frydensbjerg
f991d5434f Translated on translate.pretix.eu (Danish)
Currently translated at 47.7% (1602 of 3360 strings)

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

powered by weblate
2020-01-20 08:46:31 +00:00
Raphael Michel
7cf1688de5 PDF: Allow to use combinations of attendee name parts 2020-01-20 09:46:09 +01:00
Raphael Michel
298b3c3660 Consistently put original price in its own line 2020-01-17 17:04:13 +01:00
Raphael Michel
5ea1c96e19 Bump to 3.6.0.dev0 2020-01-12 14:44:25 +01:00
Raphael Michel
d29b8eba01 Bump to 3.5.0 2020-01-12 14:42:57 +01:00
Raphael Michel
f566b353f2 Retry more email failures 2020-01-11 14:11:20 +01:00
Raphael Michel
c2221fad32 Update from Weblate (#1544)
Update from Weblate
2020-01-11 14:00:18 +01:00
Maarten van den Berg
06a8a804f4 Translated on translate.pretix.eu (Dutch (informal))
Currently translated at 100.0% (3360 of 3360 strings)

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

powered by weblate
2020-01-11 12:54:54 +00:00
Raphael Michel
5832429540 Fix unrecognized user agents seen in the wild 2020-01-11 13:52:37 +01:00
Raphael Michel
7913de971c Fix timezone assumptions in test fixtures 2020-01-11 13:45:49 +01:00
Raphael Michel
9b91e3e4f6 Fix doc typos 2020-01-11 13:34:11 +01:00
Raphael Michel
402730df43 API: Add timezone attribute to events
Note: I still believe the issues described in https://github.com/pretix/pretix/issues/1378
are a problem, and I'm still not keen on adding settings properties to
the API until we have a proper design for it. However, I'm making an
exception here since the list of events can't be used in a very useful
way with not access to the timezone.
2020-01-11 13:24:19 +01:00
Raphael Michel
c1d6d9bf1a Downgrade openpyxl since we still support Python 3.5 2020-01-11 13:15:58 +01:00
Raphael Michel
ddbe27f351 API: Allow to return canceled positions and fees 2020-01-11 12:57:43 +01:00
Raphael Michel
35f2b10069 Compatibility with new openpyxl 2020-01-11 12:12:53 +01:00
Raphael Michel
0d2a534982 Bank transfer: Show date of last import 2020-01-09 21:41:08 +01:00
Raphael Michel
a1ad00a30c Add anchors for products/categories 2020-01-09 10:19:44 +01:00
Raphael Michel
07d2463960 Correctly set timezone when cloning events 2020-01-09 09:19:11 +01:00
Raphael Michel
08de722525 Prevent showing internal product name in question step 2020-01-09 09:19:11 +01:00
Raphael Michel
891e740ede Update from Weblate (#1541)
Update from Weblate
2020-01-08 16:52:20 +01:00
pajowu
87645a0b1f Limit Payment Term Days Field (#1542) 2020-01-08 16:52:02 +01:00
oocf
d7a575683e Translated on translate.pretix.eu (Spanish)
Currently translated at 91.6% (3077 of 3360 strings)

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

powered by weblate
2020-01-08 12:17:00 +00:00
Raphael Michel
ca83a44489 PDF Editor: Fix compatibility problems with older text objects 2020-01-08 13:16:42 +01:00
Raphael Michel
40da03f979 Improve text rendering options in PDF editor (#1540)
Improve text rendering options in PDF editor
2020-01-07 12:23:37 +01:00
Raphael Michel
fdd45a85f0 Do not send download reminders if order is placed after download date 2020-01-07 11:54:06 +01:00
Raphael Michel
47579d0517 Fix #505 -- Allow to let text flow downwards 2020-01-07 11:48:04 +01:00
Raphael Michel
8704a7f3dd Fix #1053 -- Rotation support in reportlab renderer 2020-01-07 11:26:28 +01:00
Raphael Michel
244e0695b1 PDF editor: Do not catch keyboard events inside source view 2020-01-03 18:30:33 +01:00
Raphael Michel
8e2821b398 Add a maximum budget to vouchers (#1526)
* Data model changes

* Fix test failures

* Adjustments

* Some tests and API support

* Check when extending orders

* Make things more deterministic, fix style

* Do not apply negative discounts

* Update price_before_voucher on item/subevent changes

* Add tests for price_before_voucher in combination with free price

* Fix InvoiceAddress.DoesNotExist
2020-01-03 16:15:17 +01:00
Raphael Michel
b738e3bd9d Do not show canceled payment to user 2020-01-03 10:48:57 +01:00
Raphael Michel
fa224fd17e Allow to use invoice address city in PDFs 2020-01-03 10:47:53 +01:00
Raphael Michel
76359c859f Improve logging of gift card changes and show logs 2020-01-02 17:40:11 +01:00
Katharina Bogad
ff98ae3200 Update oauthlib to ==3.1.* (#1538)
* Bumped oauthlib to ==3.1.*

* Fix tests for oauthlib 3.1

In some cases, oauthlib now returns 400 instead of 401.
2020-01-02 13:15:24 +01:00
Raphael Michel
2ffb4edee9 Import: Do not set country to NULL
PRETIXEU-1QJ
2020-01-02 10:53:01 +01:00
Raphael Michel
902f589ee6 Update from Weblate (#1536)
Update from Weblate
2020-01-02 10:11:49 +01:00
Raphael Michel
2a6dc22d7b Allow to use datetime components in invoice prefixes (#1529) 2020-01-02 09:46:07 +01:00
Abdullah
4d9ec7c8e4 Translated on translate.pretix.eu (Arabic)
Currently translated at 97.1% (100 of 103 strings)

Translation: pretix/pretix (frontend)
Translate-URL: https://translate.pretix.eu/projects/pretix/pretix-js/ar/

powered by weblate
2019-12-25 19:33:08 +00:00
Abdullah
b84a0e93ae Translated on translate.pretix.eu (Arabic)
Currently translated at 98.5% (3310 of 3359 strings)

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

powered by weblate
2019-12-25 19:33:08 +00:00
Abdullah
534f09bdc6 Translated on translate.pretix.eu (Arabic)
Currently translated at 98.5% (3310 of 3359 strings)

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

powered by weblate
2019-12-25 19:33:08 +00:00
Patrick Arminio
370aa63ead Translated on translate.pretix.eu (Italian)
Currently translated at 47.6% (49 of 103 strings)

Translation: pretix/pretix (frontend)
Translate-URL: https://translate.pretix.eu/projects/pretix/pretix-js/it/

powered by weblate
2019-12-25 19:33:08 +00:00
Raphael Michel
fb7e859e72 Ticket download: Fix error message representation 2019-12-25 20:32:22 +01:00
Raphael Michel
80a7c45e05 Fix missing checks in 38a19bb58 2019-12-25 20:26:47 +01:00
Raphael Michel
38a19bb58b Allow to download tickets through GET requests 2019-12-23 22:07:32 +01:00
Patrick Arminio
19873e2a09 Expose help texts on questions' API (#1534)
* Expose help texts on questions' API

* Update questions docs to show help_text

* Update questions.rst

Co-authored-by: Raphael Michel <mail@raphaelmichel.de>
2019-12-22 19:30:17 +01:00
Raphael Michel
eb7e938af6 Allow to explicitly set ticket language 2019-12-20 18:17:00 +01:00
Raphael Michel
614c40596f Move revoked devices to the bottom in the list of devices 2019-12-19 09:22:42 +01:00
Raphael Michel
4db56e218e Update from Weblate (#1530)
Update from Weblate
2019-12-19 08:56:49 +01:00
Abdullah
ed9b96a41c Translated on translate.pretix.eu (Arabic)
Currently translated at 98.5% (3310 of 3359 strings)

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

powered by weblate
2019-12-19 02:00:10 +00:00
Raphael Michel
e839dbc7d4 Emulate secure request in samesite tests 2019-12-18 19:37:43 +01:00
Raphael Michel
982fb0149d Never set SameSite=None without HTTPS 2019-12-18 19:03:17 +01:00
Raphael Michel
4597cb9849 Drop typeahead for seats 2019-12-18 13:48:15 +01:00
Raphael Michel
9f629fc1c9 Do not show subject prefix in HTML email headline 2019-12-17 11:09:05 +01:00
Raphael Michel
387e1b4998 Fix issue that blocks seat sold in canceled position 2019-12-16 14:00:08 +01:00
Raphael Michel
84415864e5 Note cloning of objects to log 2019-12-16 14:00:08 +01:00
Maico Timmerman
82feca6e38 Fix #1521 -- External authenticated users cannot delete events (#1523)
* Remove check password for event deletion, instead require recent login.

* Reauthenticate for backends using authentication_url.

* Require recent login for data shredder and prompt slug instead of password.

* Fix tests for recent login required on event delete and data shred.

* Pull request remarks for recent login required for event delete and data shred.

* Remove unused imported check_password.
2019-12-16 10:45:01 +01:00
Maico Timmerman
28242e52aa Fix #1522 -- Login button redirects to authentication url with… (#1525) 2019-12-16 10:42:51 +01:00
Raphael Michel
488ee19b11 Set direction:rtl in emails 2019-12-16 10:35:54 +01:00
Raphael Michel
ba4f00cfc0 Update from Weblate (#1520)
Update from Weblate
2019-12-16 10:33:56 +01:00
Maarten van den Berg
eb392ebf20 Translated on translate.pretix.eu (Dutch (informal))
Currently translated at 100.0% (103 of 103 strings)

Translation: pretix/pretix (frontend)
Translate-URL: https://translate.pretix.eu/projects/pretix/pretix-js/nl_Informal/

powered by weblate
2019-12-16 08:54:34 +00:00
Maarten van den Berg
3cef690779 Translated on translate.pretix.eu (Dutch (informal))
Currently translated at 100.0% (3360 of 3360 strings)

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

powered by weblate
2019-12-16 08:54:34 +00:00
Abdullah
294fc4735a Translated on translate.pretix.eu (Arabic)
Currently translated at 98.5% (3310 of 3359 strings)

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

powered by weblate
2019-12-16 08:54:34 +00:00
Abdullah
6d17cad529 Translated on translate.pretix.eu (Arabic)
Currently translated at 98.5% (3310 of 3359 strings)

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

powered by weblate
2019-12-16 08:54:34 +00:00
Abdullah
668380cc3f Translated on translate.pretix.eu (Arabic)
Currently translated at 98.5% (3310 of 3359 strings)

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

powered by weblate
2019-12-16 08:54:34 +00:00
Abdullah
3bf8de39a0 Translated on translate.pretix.eu (Arabic)
Currently translated at 98.5% (3310 of 3359 strings)

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

powered by weblate
2019-12-16 08:54:34 +00:00
saad91
1986cdf4b9 Translated on translate.pretix.eu (Arabic)
Currently translated at 98.5% (3310 of 3359 strings)

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

powered by weblate
2019-12-16 08:54:34 +00:00
Raphael Michel
577729a271 Add customer data to OrderTaxListReport 2019-12-16 09:54:16 +01:00
Raphael Michel
9033e5b6f7 Propose a gift card code when creating new cards 2019-12-16 09:45:36 +01:00
Raphael Michel
c1fa0d1559 Fix #1524 -- Bug in CartManager's max_per_item validation 2019-12-16 09:45:36 +01:00
Raphael Michel
e1a4dd6e43 Revert "Data model changes"
This reverts commit 089a468a5d.
2019-12-15 19:00:02 +01:00
Raphael Michel
089a468a5d Data model changes 2019-12-15 18:28:51 +01:00
Raphael Michel
018d345008 Add trust-x-forwarded-proto settings 2019-12-14 13:37:44 +01:00
Raphael Michel
529e2a0286 Re-set redeemed property when copying vouchers 2019-12-13 15:52:27 +01:00
Raphael Michel
1d36ef3c24 Allow to ignore plugin conflicts via environment 2019-12-13 12:57:25 +01:00
Raphael Michel
282ad2c869 Do not check compatibiliy while upgrading 2019-12-13 12:55:33 +01:00
Raphael Michel
e67ff83378 Do not allow to create negative gift cards through the API 2019-12-12 14:18:47 +01:00
Raphael Michel
21be22e489 Add typeahead when filling event meta parameters 2019-12-12 12:21:53 +01:00
Raphael Michel
3da79ad36b Remove positivity constraint in apply_voucher 2019-12-12 12:02:12 +01:00
Raphael Michel
8a17fedaa6 Clarify show_vouchers constraint with subevents 2019-12-12 11:56:36 +01:00
Raphael Michel
7d6b3e7140 Set sales channel on all cart operations 2019-12-12 10:06:00 +01:00
Raphael Michel
f80ba365a5 Fix test for voucher csv 2019-12-11 18:13:38 +01:00
Raphael Michel
8156cdd539 Add seat to voucher CSV export 2019-12-11 17:30:53 +01:00
Raphael Michel
cd55146867 Add request and subevent parameters to front page widgets 2019-12-11 17:05:05 +01:00
Raphael Michel
3cb7482bae Add signal pretix.presale.signals.front_page_bottom_widget 2019-12-11 17:04:59 +01:00
Raphael Michel
99f3db04a9 Allow to redeem a voucher for an existing cart (#1517)
* Allow to redeem a voucher for an existing cart

* Bundle behaviour
2019-12-11 15:58:22 +01:00
Raphael Michel
352942b7d6 Allow sale of blocked seats on specific channels (#1518)
* Allow sale of blocked seats on specific channels

* Add docs
2019-12-11 15:56:20 +01:00
Raphael Michel
6d3ccc0182 More useful titles in select2 widget for seats 2019-12-11 13:05:04 +01:00
Raphael Michel
49b73fc096 Fix redemption of all-product vouchers with seating plans 2019-12-11 12:06:23 +01:00
Raphael Michel
24b931e1c3 Allow to import orders (#1516)
* Allow to import orders

* seats, subevents

* Plugin support

* Add docs

* Warn about lack of quota handling

* Control interface test

* Test skeleton

* First tests for the impotr columns

* Add tests for all columns

* Fix question validation
2019-12-11 11:44:06 +01:00
Raphael Michel
1c99e01af9 Fix test failure introduced in last commit 2019-12-11 11:22:52 +01:00
Raphael Michel
66183e805e Check-in list export: Filter by checkin_attention 2019-12-11 09:16:58 +01:00
Raphael Michel
d33c9332c6 Show event time in list of events on organizer page 2019-12-11 09:11:54 +01:00
Raphael Michel
2284def607 Fix package name of dependency 2019-12-10 18:10:29 +01:00
Raphael Michel
15c25a5a0d PDF renderer: Support for arabic 2019-12-10 17:57:48 +01:00
Martin Gross
cf5ac6af4b Organizer-level override for giftcard code length 2019-12-09 13:55:26 +01:00
Raphael Michel
2a929200b5 Vouchers: Fix CSV export for all-product vouchers 2019-12-09 10:23:50 +01:00
Raphael Michel
3f77d34026 Use the arab league flag to represent Arabic, for now
https://www.quora.com/Which-flag-represents-the-Arabic-language
http://www.flagsarenotlanguages.com/blog/the-arab-league-flag-for-arabic-language/
2019-12-07 15:30:14 +01:00
Raphael Michel
a395b24b80 Add arabic, re-order languages 2019-12-07 15:08:57 +01:00
Raphael Michel
984ef60099 Fix issues in translation 2019-12-07 15:06:15 +01:00
saad91
5b6f0df963 Translated on translate.pretix.eu (Arabic)
Currently translated at 98.5% (3309 of 3359 strings)

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

powered by weblate
2019-12-07 13:56:30 +00:00
saad91
509c7d98cc Translated on translate.pretix.eu (Arabic)
Currently translated at 97.4% (3271 of 3359 strings)

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

powered by weblate
2019-12-07 13:20:50 +00:00
saad91
3bd4959efe Translated on translate.pretix.eu (Arabic)
Currently translated at 97.4% (3271 of 3359 strings)

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

powered by weblate
2019-12-07 13:20:50 +00:00
Maarten van den Berg
4faaa8e521 Translated on translate.pretix.eu (Dutch)
Currently translated at 100.0% (103 of 103 strings)

Translation: pretix/pretix (frontend)
Translate-URL: https://translate.pretix.eu/projects/pretix/pretix-js/nl/

powered by weblate
2019-12-07 13:20:49 +00:00
Maarten van den Berg
0e8832fd54 Translated on translate.pretix.eu (Dutch)
Currently translated at 100.0% (3360 of 3360 strings)

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

powered by weblate
2019-12-07 13:20:49 +00:00
Raphael Michel
4faa76d9c7 Translated on translate.pretix.eu (Arabic)
Currently translated at 98.5% (3274 of 3323 strings)

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

powered by weblate
2019-12-07 13:20:49 +00:00
Raphael Michel
8d1f9bf0f3 Fix TypeError during widget loading 2019-12-07 14:18:04 +01:00
Raphael Michel
4afef62cbd Fix typo 2019-12-07 13:24:35 +01:00
Raphael Michel
3d5cfdd9c7 Fix conflict between are-you-sure.js and async tasks
Thanks @luto for reporting and helping to debug
2019-12-07 13:23:33 +01:00
Raphael Michel
b3b1d09690 Use "Tax Invoice" as the invoice headline in Australia 2019-12-07 12:12:20 +01:00
Raphael Michel
381ecd6d75 Update German translation 2019-12-06 20:47:51 +01:00
Raphael Michel
a12fea71e5 Include expire date on invoices 2019-12-06 20:43:01 +01:00
Raphael Michel
a6dd6ac537 Fix AttributeError in e275677a0 2019-12-06 20:31:17 +01:00
Raphael Michel
c3041aa8c4 Fix ItemBundle.MultipleObjectsReturned error when extending cart lifetimes 2019-12-06 20:30:35 +01:00
Raphael Michel
e275677a0a Default to modern invoice renderer for new events 2019-12-06 20:25:05 +01:00
Raphael Michel
fff14c31ba Add Event.set_defaults 2019-12-06 20:24:34 +01:00
Raphael Michel
a74bde60eb Show invoice address form once again before generating a new invoice 2019-12-06 20:03:22 +01:00
Raphael Michel
12b9d23efb Hide "Generate invoice" button if no payment method is selected 2019-12-06 20:03:11 +01:00
Raphael Michel
afec39ce57 Fix exception when submitting cart positions with invalid subevent IDs 2019-12-06 15:58:13 +01:00
Raphael Michel
4ae22c4a1e Bump to 3.5.0.dev0 2019-12-06 15:36:27 +01:00
314 changed files with 117239 additions and 72998 deletions

View File

@@ -4,7 +4,7 @@ pid /var/run/nginx.pid;
daemon off;
events {
worker_connections 768;
worker_connections 4096;
}
http {
@@ -39,7 +39,7 @@ http {
include /etc/nginx/conf.d/*.conf;
server {
listen 80 default_server;
listen 80 backlog=4096 default_server;
listen [::]:80 ipv6only=on default_server;
server_name _;
index index.php index.html;

View File

@@ -90,6 +90,11 @@ Example::
proxy that actively removes and re-adds the header to make sure the correct client IP is the first value.
Defaults to ``off``.
``trust_x_forwarded_proto``
Specifies whether the ``X-Forwarded-Proto`` header can be trusted. Only set to ``on`` if you have a reverse
proxy that actively removes and re-adds the header to make sure the correct client IP is the first value.
Defaults to ``off``.
Locale settings
---------------

View File

@@ -125,6 +125,8 @@ Fill the configuration file ``/etc/pretix/pretix.cfg`` with the following conten
; DO NOT change the following value, it has to be set to the location of the
; directory *inside* the docker container
datadir=/data
trust_x_forwarded_for=on
trust_x_forwarded_proto=on
[database]
; Replace postgresql with mysql for MySQL
@@ -180,6 +182,7 @@ named ``/etc/systemd/system/pretix.service`` with the following content::
-v /var/pretix-data:/data \
-v /etc/pretix:/etc/pretix \
-v /var/run/redis:/var/run/redis \
--sysctl net.core.somaxconn=4096
pretix/standalone:stable all
ExecStop=/usr/bin/docker stop %n

View File

@@ -85,6 +85,8 @@ Fill the configuration file ``/etc/pretix/pretix.cfg`` with the following conten
url=https://pretix.mydomain.com
currency=EUR
datadir=/var/pretix/data
trust_x_forwarded_for=on
trust_x_forwarded_proto=on
[database]
; For MySQL, replace with "mysql"

View File

@@ -170,6 +170,19 @@ Date String in ISO 8601 format ``2017-12-27``
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"``,
format *or* specification of ``"RELDATE/3/12:00:00/presale_start/"``
a relative datetime,
constructed from a number of
days before the base point,
a time of day, and the base
point.
Relative date *either* String in ISO 8601 ``"2017-12-27"``,
format *or* specification of ``"RELDATE/3/-/presale_start/"``
a relative date,
constructed from a number of
days before the base point
and the base point.
===================== ============================ ===================================
Query parameters

View File

@@ -61,7 +61,7 @@ access to the API. The ``token`` endpoint expects you to authenticate using `HTT
ID as a username and your client secret as a password. You are also required to again supply the same ``redirect_uri``
parameter that you used for the authorization.
.. http:get:: /api/v1/oauth/token
.. http:post:: /api/v1/oauth/token
Request a new access token

View File

@@ -0,0 +1,148 @@
pretix Hosted reseller API
==========================
This API is only accessible to our `value-added reseller partners`_ on pretix Hosted.
.. note:: This API is only accessible with user-level permissions, not with API tokens. Therefore, you will need to
create an :ref:`OAuth application <rest-oauth>` and obtain an OAuth access token for a user account that has
permission to your reseller account.
Reseller account resource
-------------------------
The resource contains the following public fields:
.. rst-class:: rest-resource-table
===================================== ========================== =======================================================
Field Type Description
===================================== ========================== =======================================================
id integer Your reseller ID
name string Internal name of your reseller account
public_name string Public name of your reseller account
public_url string Public URL of your company
support_email string Your support email address
support_phone string Your support phone number
communication_language string Language code we use to communicate with you
===================================== ========================== =======================================================
Endpoints
---------
.. http:get:: /api/v1/var/
Returns a list of all reseller accounts you have access to.
**Example request**:
.. sourcecode:: http
GET /api/v1/var/ HTTP/1.1
Host: pretix.eu
Accept: application/json, text/javascript
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Vary: Accept
Content-Type: application/json
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": 1,
"name": "ticketshop.live Ltd & Co. KG",
"public_name": "ticketshop.live",
"public_url": "https://ticketshop.live",
"support_email": "support@ticketshop.live",
"support_phone": "+4962213217750",
"communication_language": "de"
}
]
}
:query integer page: The page number in case of a multi-page result set, default is 1
:statuscode 200: no error
:statuscode 401: Authentication failure
.. http:get:: /api/v1/var/(id)/
Returns information on one reseller account, identified by its ID.
**Example request**:
.. sourcecode:: http
GET /api/v1/var/1/ HTTP/1.1
Host: pretix.eu
Accept: application/json, text/javascript
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Vary: Accept
Content-Type: application/json
{
"id": 1,
"name": "ticketshop.live Ltd & Co. KG",
"public_name": "ticketshop.live",
"public_url": "https://ticketshop.live",
"support_email": "support@ticketshop.live",
"support_phone": "+4962213217750",
"communication_language": "de"
}
:param id: The ``id`` field of the reseller account to fetch
:statuscode 200: no error
:statuscode 401: Authentication failure
:statuscode 404: The requested account does not exist **or** you have no permission to view this resource.
.. http:post:: /api/v1/var/(id)/create_organizer/
Creates a new organizer account that will be associated with a given reseller account.
**Example request**:
.. sourcecode:: http
POST /api/v1/var/1/create_organizer/ HTTP/1.1
Host: pretix.eu
Accept: application/json, text/javascript
Content-Type: application/json
Content-Length: 123
{
"name": "My new client",
"slug": "New client"
}
**Example response**:
.. sourcecode:: http
HTTP/1.1 201 Created
Vary: Accept
Content-Type: application/json
{
"id": 1,
"name": "My new client",
"slug": "New client"
}
:param id: The ``id`` field of the reseller account to fetch
:statuscode 201: no error
:statuscode 400: Invalid request body, usually the slug is invalid or already taken.
:statuscode 401: Authentication failure
:statuscode 404: The requested account does not exist **or** you have no permission to view this resource.
.. _value-added reseller partners: https://pretix.eu/about/en/var

View File

@@ -194,6 +194,7 @@ Cart position endpoints
* ``subevent`` (optional)
* ``expires`` (optional)
* ``includes_tax`` (optional)
* ``sales_channel`` (optional)
* ``answers``
* ``question``

View File

@@ -42,6 +42,7 @@ seating_plan integer If reserved sea
plan. Otherwise ``null``.
seat_category_mapping object An object mapping categories of the seating plan
(strings) to items in the event (integers or ``null``).
timezone string Event timezone name
===================================== ========================== =======================================================
@@ -74,6 +75,10 @@ seat_category_mapping object An object mappi
The attributes ``geo_lat`` and ``geo_lon`` have been added.
.. versionchanged:: 3.4
The attribute ``timezone`` has been added.
Endpoints
---------
@@ -127,6 +132,7 @@ Endpoints
"meta_data": {},
"seating_plan": null,
"seat_category_mapping": {},
"timezone": "Europe/Berlin",
"plugins": [
"pretix.plugins.banktransfer"
"pretix.plugins.stripe"
@@ -197,6 +203,7 @@ Endpoints
"seating_plan": null,
"seat_category_mapping": {},
"meta_data": {},
"timezone": "Europe/Berlin",
"plugins": [
"pretix.plugins.banktransfer"
"pretix.plugins.stripe"
@@ -248,6 +255,7 @@ Endpoints
"geo_lon": null,
"has_subevents": false,
"meta_data": {},
"timezone": "Europe/Berlin",
"plugins": [
"pretix.plugins.stripe",
"pretix.plugins.paypal"
@@ -281,6 +289,7 @@ Endpoints
"seat_category_mapping": {},
"has_subevents": false,
"meta_data": {},
"timezone": "Europe/Berlin",
"plugins": [
"pretix.plugins.stripe",
"pretix.plugins.paypal"
@@ -334,6 +343,7 @@ Endpoints
"seat_category_mapping": {},
"has_subevents": false,
"meta_data": {},
"timezone": "Europe/Berlin",
"plugins": [
"pretix.plugins.stripe",
"pretix.plugins.paypal"
@@ -367,6 +377,7 @@ Endpoints
"seating_plan": null,
"seat_category_mapping": {},
"meta_data": {},
"timezone": "Europe/Berlin",
"plugins": [
"pretix.plugins.stripe",
"pretix.plugins.paypal"
@@ -432,6 +443,7 @@ Endpoints
"seating_plan": null,
"seat_category_mapping": {},
"meta_data": {},
"timezone": "Europe/Berlin",
"plugins": [
"pretix.plugins.banktransfer",
"pretix.plugins.stripe",
@@ -474,3 +486,123 @@ Endpoints
:statuscode 204: no error
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer/event does not exist **or** you have no permission to delete this resource.
Event settings
--------------
pretix events have lots and lots of parameters of different types that are stored in a key-value store on our system.
Since many of these settings depend on each other in complex ways, we can not give direct access to all of these
settings through the API. However, we do expose many of the simple and useful flags through the API.
Please note that the available settings flags change between pretix versions and also between events, depending on the
installed plugins, and we do not give a guarantee on backwards-compatibility like with other parts of the API.
Therefore, we're also not including a list of the options here, but instead recommend to look at the endpoint output
to see available options. The ``explain=true`` flag enables a verbose mode that provides you with human-readable
information about the properties.
.. note:: Please note that this is not a complete representation of all event settings. You will find more settings
in the web interface.
.. warning:: This API is intended for advanced users. Even though we take care to validate your input, you will be
able to break your event using this API by creating situations of conflicting settings. Please take care.
.. versionchanged:: 3.6
Initial support for settings has been added to the API.
.. http:get:: /api/v1/organizers/(organizer)/events/(event)/settings/
Get current values of event settings.
Permission required: "Can change event settings"
**Example request**:
.. sourcecode:: http
GET /api/v1/organizers/bigevents/events/sampleconf/settings/ HTTP/1.1
Host: pretix.eu
Accept: application/json, text/javascript
**Example standard response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Vary: Accept
Content-Type: application/json
{
"imprint_url": "https://pretix.eu",
}
**Example verbose response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Vary: Accept
Content-Type: application/json
{
"imprint_url":
{
"value": "https://pretix.eu",
"label": "Imprint URL",
"help_text": "This should point e.g. to a part of your website that has your contact details and legal information."
}
},
}
:param organizer: The ``slug`` field of the organizer of the event to access
:param event: The ``slug`` field of the event to access
:query explain: Set to ``true`` to enable verbose response mode
:statuscode 200: no error
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer/event does not exist **or** you have no permission to view this resource.
.. http:patch:: /api/v1/organizers/(organizer)/events/(event)/settings/
Updates event settings. Note that ``PUT`` is not allowed here, only ``PATCH``.
.. warning::
Settings can be stored at different levels in pretix. If a value is not set on event level, a default setting
from a higher level (organizer, global) will be returned. If you explicitly set a setting on event level, it
will no longer be inherited from the higher levels. Therefore, we recommend you to send only settings that you
explicitly want to set on event level. To unset a settings, pass ``null``.
**Example request**:
.. sourcecode:: http
PATCH /api/v1/organizers/bigevents/events/sampleconf/settings/ HTTP/1.1
Host: pretix.eu
Accept: application/json, text/javascript
Content-Type: application/json
{
"imprint_url": "https://example.org/imprint/"
}
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Vary: Accept
Content-Type: application/json
{
"imprint_url": "https://example.org/imprint/",
}
:param organizer: The ``slug`` field of the organizer of the event to update
:param event: The ``slug`` field of the event to update
:statuscode 200: no error
:statuscode 400: The event could not be updated due to invalid submitted data.
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer/event does not exist **or** you have no permission to create this resource.

View File

@@ -221,9 +221,14 @@ Endpoints
"value": "15.37"
}
.. versionchanged:: 3.5
This endpoint now returns status code ``409`` if the transaction would lead to a negative gift card value.
:param organizer: The ``slug`` field of the organizer to modify
:param id: The ``id`` field of the gift card to modify
:statuscode 200: no error
:statuscode 400: The gift card could not be modified due to invalid submitted data
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer does not exist **or** you have no permission to change this resource.
:statuscode 409: There is not sufficient credit on the gift card.

View File

@@ -23,6 +23,8 @@ Resources and endpoints
waitinglist
giftcards
carts
teams
webhooks
seatingplans
billing_invoices
billing_var

View File

@@ -61,9 +61,10 @@ invoice_address object Invoice address
└ vat_id_validated string ``true``, if the VAT ID has been validated against the
EU VAT service and validation was successful. This only
happens in rare cases.
positions list of objects List of non-canceled order positions (see below)
fees list of objects List of non-canceled fees included in the order total
(i.e. payment fees)
positions list of objects List of order positions (see below). By default, only
non-canceled positions are included.
fees list of objects List of fees included in the order total. By default, only
non-canceled fees are included.
├ fee_type string Type of fee (currently ``payment``, ``passbook``,
``other``)
├ value money (string) Fee amount
@@ -72,7 +73,8 @@ fees list of objects List of non-can
can be empty
├ tax_rate decimal (string) VAT rate applied for this fee
├ tax_value money (string) VAT included in this fee
tax_rule integer The ID of the used tax rule (or ``null``)
tax_rule integer The ID of the used tax rule (or ``null``)
└ canceled boolean Whether or not this fee has been canceled.
downloads list of objects List of ticket download options for order-wise ticket
downloading. This might be a multi-page PDF or a ZIP
file of tickets for outputs that do not support
@@ -145,6 +147,10 @@ last_modified datetime Last modificati
The ``invoice_address.state`` and ``url`` attributes have been added. When creating orders through the API,
vouchers are now supported and many fields are now optional.
.. versionchanged:: 3.5
The ``order.fees.canceled`` attribute has been added.
.. _order-position-resource:
@@ -159,6 +165,8 @@ Field Type Description
id integer Internal ID of the order position
order string Order code of the order the position belongs to
positionid integer Number of the position within the order
canceled boolean Whether or not this position has been canceled. Note that
by default, only non-canceled positions are shown.
item integer ID of the purchased item
variation integer ID of the purchased variation (or ``null``)
price money (string) Price of this position
@@ -224,6 +232,10 @@ pdf_data object Data object req
The ``url`` of a ticket ``download`` can now also return a ``text/uri-list`` instead of a file. See
:ref:`order-position-ticket-download` for details.
.. versionchanged:: 3.5
The attribute ``canceled`` has been added.
.. _order-payment-resource:
Order payment resource
@@ -290,6 +302,10 @@ List of all orders
Filtering for emails or order codes is now case-insensitive.
.. versionchanged:: 3.5
The ``include_canceled_positions`` and ``include_canceled_fees`` query parameters have been added.
.. http:get:: /api/v1/organizers/(organizer)/events/(event)/orders/
Returns a list of all orders within a given event.
@@ -355,6 +371,7 @@ List of all orders
"id": 23442,
"order": "ABC12",
"positionid": 1,
"canceled": false,
"item": 1345,
"variation": null,
"price": "23.00",
@@ -427,6 +444,9 @@ List of all orders
:query boolean testmode: Only return orders with ``testmode`` set to ``true`` or ``false``
:query boolean require_approval: If set to ``true`` or ``false``, only categories with this value for the field
``require_approval`` will be returned.
:query include_canceled_positions: If set to ``true``, the output will contain canceled order positions. Note that this
only affects position-level cancellations, not fully-canceled orders.
:query include_canceled_fees: If set to ``true``, the output will contain canceled order fees.
:query string email: Only return orders created with the given email address
:query string locale: Only return orders with the given customer locale
:query datetime modified_since: Only return orders that have changed since the given date. Be careful: We only
@@ -444,6 +464,10 @@ List of all orders
Fetching individual orders
--------------------------
.. versionchanged:: 3.5
The ``include_canceled_positions`` and ``include_canceled_fees`` query parameters have been added.
.. http:get:: /api/v1/organizers/(organizer)/events/(event)/orders/(code)/
Returns information on one order, identified by its order code.
@@ -503,6 +527,7 @@ Fetching individual orders
"id": 23442,
"order": "ABC12",
"positionid": 1,
"canceled": false,
"item": 1345,
"variation": null,
"price": "23.00",
@@ -568,6 +593,9 @@ Fetching individual orders
:param organizer: The ``slug`` field of the organizer to fetch
:param event: The ``slug`` field of the event to fetch
:param code: The ``code`` field of the order to fetch
:query include_canceled_positions: If set to ``true``, the output will contain canceled order positions. Note that this
only affects position-level cancellations, not fully-canceled orders.
:query include_canceled_fees: If set to ``true``, the output will contain canceled order fees.
:statuscode 200: no error
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer/event does not exist **or** you have no permission to view this resource.
@@ -1313,8 +1341,9 @@ List of all order positions
The value ``auto_checked_in`` has been added to the ``checkins``-attribute.
.. versionchanged:: 3.5
.. note:: Individually canceled order positions are currently not visible via the API at all.
The ``include_canceled_positions`` and ``include_canceled_fees`` query parameters have been added.
.. http:get:: /api/v1/organizers/(organizer)/events/(event)/orderpositions/
@@ -1345,6 +1374,7 @@ List of all order positions
"id": 23442,
"order": "ABC12",
"positionid": 1,
"canceled": false,
"item": 1345,
"variation": null,
"price": "23.00",
@@ -1414,6 +1444,8 @@ List of all order positions
comma-separated IDs.
:query string voucher: Only return positions with a specific voucher.
:query string voucher__code: Only return positions with a specific voucher code.
:query include_canceled_positions: If set to ``true``, the output will contain canceled order positions. Note that this
only affects position-level cancellations, not fully-canceled orders.
:param organizer: The ``slug`` field of the organizer to fetch
:param event: The ``slug`` field of the event to fetch
:statuscode 200: no error
@@ -1447,6 +1479,7 @@ Fetching individual positions
"id": 23442,
"order": "ABC12",
"positionid": 1,
"canceled": false,
"item": 1345,
"variation": null,
"price": "23.00",
@@ -1491,6 +1524,7 @@ Fetching individual positions
:param organizer: The ``slug`` field of the organizer to fetch
:param event: The ``slug`` field of the event to fetch
:param id: The ``id`` field of the order position to fetch
:query include_canceled_positions: If set to ``true``, canceled positions may be returned (otherwise, they return 404).
:statuscode 200: no error
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer/event does not exist **or** you have no permission to view this resource.
@@ -1587,6 +1621,10 @@ Order payment endpoints
These endpoints have been added.
.. versionchanged:: 3.6
Payments can now be created through the API.
.. http:get:: /api/v1/organizers/(organizer)/events/(event)/orders/(code)/payments/
Returns a list of all payments for an order.
@@ -1795,6 +1833,61 @@ Order payment endpoints
:statuscode 403: The requested organizer/event does not exist **or** you have no permission to view this resource.
:statuscode 404: The requested order or payment does not exist.
.. http:post:: /api/v1/organizers/(organizer)/events/(event)/orders/(code)/payments/
Creates a new payment.
Be careful with the ``info`` parameter: You can pass a nested JSON object that will be set as the internal ``info``
value of the payment object that will be created. How this value is handled is up to the payment provider and you
should only use this if you know the specific payment provider in detail. Please keep in mind that the payment
provider will not be called to do anything about this (i.e. if you pass a bank account to a debit provider, *no*
charge will be created), this is just informative in case you *handled the payment already*.
**Example request**:
.. sourcecode:: http
POST /api/v1/organizers/bigevents/events/sampleconf/orders/ABC12/payments/ HTTP/1.1
Host: pretix.eu
Accept: application/json, text/javascript
Content-Type: application/json
{
"state": "confirmed",
"amount": "23.00",
"payment_date": "2017-12-04T12:13:12Z",
"info": {},
"provider": "banktransfer"
}
**Example response**:
.. sourcecode:: http
HTTP/1.1 201 Created
Vary: Accept
Content-Type: application/json
{
"local_id": 1,
"state": "confirmed",
"amount": "23.00",
"created": "2017-12-01T10:00:00Z",
"payment_date": "2017-12-04T12:13:12Z",
"payment_url": null,
"details": {},
"provider": "banktransfer"
}
:param organizer: The ``slug`` field of the organizer to access
:param event: The ``slug`` field of the event to access
:param order: The ``code`` field of the order to access
:statuscode 201: no error
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer/event does not exist **or** you have no permission to view this resource.
:statuscode 404: The requested order does not exist.
Order refund endpoints
----------------------
@@ -1913,7 +2006,8 @@ Order refund endpoints
"payment": 1,
"execution_date": null,
"provider": "manual",
"mark_canceled": false
"mark_canceled": false,
"mark_pending": true
}
**Example response**:

View File

@@ -18,6 +18,7 @@ Field Type Description
===================================== ========================== =======================================================
id integer Internal ID of the question
question multi-lingual string The field label shown to the customer
help_text multi-lingual string The help text shown to the customer
type string The expected type of answer. Valid options:
* ``N`` number
@@ -87,6 +88,10 @@ dependency_value string An old version
The attribute ``print_on_invoice`` has been added.
.. versionchanged:: 3.5
The attribute ``help_text`` has been added.
Endpoints
---------
@@ -123,6 +128,7 @@ Endpoints
{
"id": 1,
"question": {"en": "T-Shirt size"},
"help_text": {"en": "Choose your preferred t-shirt-size"},
"type": "C",
"required": false,
"items": [1, 2],
@@ -193,6 +199,7 @@ Endpoints
{
"id": 1,
"question": {"en": "T-Shirt size"},
"help_text": {"en": "Choose your preferred t-shirt-size"},
"type": "C",
"required": false,
"items": [1, 2],
@@ -248,6 +255,7 @@ Endpoints
{
"question": {"en": "T-Shirt size"},
"help_text": {"en": "Choose your preferred t-shirt-size"},
"type": "C",
"required": false,
"items": [1, 2],
@@ -282,6 +290,7 @@ Endpoints
{
"id": 1,
"question": {"en": "T-Shirt size"},
"help_text": {"en": "Choose your preferred t-shirt-size"},
"type": "C",
"required": false,
"items": [1, 2],
@@ -356,6 +365,7 @@ Endpoints
{
"id": 1,
"question": {"en": "T-Shirt size"},
"help_text": {"en": "Choose your preferred t-shirt-size"},
"type": "C",
"required": false,
"items": [1, 2],

671
doc/api/resources/teams.rst Normal file
View File

@@ -0,0 +1,671 @@
.. spelling:: fullname
.. _`rest-teams`:
Teams
=====
.. warning:: Unlike our user interface, the team API **does** allow you to lock yourself out by deleting or modifying
the team your user or API key belongs to. Be careful around here!
Team resource
-------------
The team resource contains the following public fields:
.. rst-class:: rest-resource-table
===================================== ========================== =======================================================
Field Type Description
===================================== ========================== =======================================================
id integer Internal ID of the team
name string Team name
all_events boolean Whether this team has access to all events
limit_events list List of event slugs this team has access to
can_create_events boolean
can_change_teams boolean
can_change_organizer_settings boolean
can_manage_gift_cards boolean
can_change_event_settings boolean
can_change_items boolean
can_view_orders boolean
can_change_orders boolean
can_view_vouchers boolean
can_change_vouchers boolean
===================================== ========================== =======================================================
Team member resource
--------------------
The team member resource contains the following public fields:
.. rst-class:: rest-resource-table
===================================== ========================== =======================================================
Field Type Description
===================================== ========================== =======================================================
id integer Internal ID of the user
email string The user's email address
fullname string The user's full name (or ``null``)
require_2fa boolean Whether this user uses two-factor-authentication
===================================== ========================== =======================================================
Team invite resource
--------------------
The team invite resource contains the following public fields:
.. rst-class:: rest-resource-table
===================================== ========================== =======================================================
Field Type Description
===================================== ========================== =======================================================
id integer Internal ID of the invite
email string The invitee's email address
===================================== ========================== =======================================================
Team API token resource
-----------------------
The team API token resource contains the following public fields:
.. rst-class:: rest-resource-table
===================================== ========================== =======================================================
Field Type Description
===================================== ========================== =======================================================
id integer Internal ID of the invite
name string Name of this API token
active boolean Whether this API token is active (can never be set to
``true`` again once ``false``)
token string The actual API token. Will only be sent back during
token creation.
===================================== ========================== =======================================================
Team endpoints
--------------
.. http:get:: /api/v1/organizers/(organizer)/teams/
Returns a list of all teams within a given organizer.
**Example request**:
.. sourcecode:: http
GET /api/v1/organizers/bigevents/teams/ HTTP/1.1
Host: pretix.eu
Accept: application/json, text/javascript
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Vary: Accept
Content-Type: application/json
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": 1,
"name": "Admin team",
"all_events": true,
"limit_events": [],
"can_create_events": true,
...
}
]
}
:query integer page: The page number in case of a multi-page result set, default is 1
:param organizer: The ``slug`` field of the organizer to fetch
:statuscode 200: no error
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer does not exist **or** you have no permission to view this resource.
.. http:get:: /api/v1/organizers/(organizer)/teams/(id)/
Returns information on one team, identified by its ID.
**Example request**:
.. sourcecode:: http
GET /api/v1/organizers/bigevents/teams/1/ HTTP/1.1
Host: pretix.eu
Accept: application/json, text/javascript
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Vary: Accept
Content-Type: application/json
{
"id": 1,
"name": "Admin team",
"all_events": true,
"limit_events": [],
"can_create_events": true,
...
}
:param organizer: The ``slug`` field of the organizer to fetch
:param id: The ``id`` field of the team to fetch
:statuscode 200: no error
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer does not exist **or** you have no permission to view this resource.
.. http:post:: /api/v1/organizers/(organizer)/teams/
Creates a new team
**Example request**:
.. sourcecode:: http
POST /api/v1/organizers/bigevents/teams/ HTTP/1.1
Host: pretix.eu
Accept: application/json, text/javascript
Content-Type: application/json
{
"name": "Admin team",
"all_events": true,
"limit_events": [],
"can_create_events": true,
...
}
**Example response**:
.. sourcecode:: http
HTTP/1.1 201 Created
Vary: Accept
Content-Type: application/json
{
"id": 2,
"name": "Admin team",
"all_events": true,
"limit_events": [],
"can_create_events": true,
...
}
:param organizer: The ``slug`` field of the organizer to create a team for
:statuscode 201: no error
:statuscode 400: The team could not be created due to invalid submitted data.
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer does not exist **or** you have no permission to create this resource.
.. http:patch:: /api/v1/organizers/(organizer)/teams/(id)/
Update a team. You can also use ``PUT`` instead of ``PATCH``. With ``PUT``, you have to provide all fields of
the resource, other fields will be reset to default. With ``PATCH``, you only need to provide the fields that you
want to change.
**Example request**:
.. sourcecode:: http
PATCH /api/v1/organizers/bigevents/teams/1/ HTTP/1.1
Host: pretix.eu
Accept: application/json, text/javascript
Content-Type: application/json
Content-Length: 94
{
"can_create_events": true
}
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Vary: Accept
Content-Type: application/json
{
"id": 1,
"name": "Admin team",
"all_events": true,
"limit_events": [],
"can_create_events": true,
...
}
:param organizer: The ``slug`` field of the organizer to modify
:param id: The ``id`` field of the team to modify
:statuscode 200: no error
:statuscode 400: The team could not be modified due to invalid submitted data
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer does not exist **or** you have no permission to change this resource.
.. http:delete:: /api/v1/organizers/(organizer)/teams/(id)/
Deletes a team.
**Example request**:
.. sourcecode:: http
DELETE /api/v1/organizers/bigevents/teams/1/ HTTP/1.1
Host: pretix.eu
Accept: application/json, text/javascript
**Example response**:
.. sourcecode:: http
HTTP/1.1 204 No Content
:param organizer: The ``slug`` field of the organizer to modify
:param id: The ``id`` field of the team to delete
:statuscode 204: no error
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer does not exist **or** you have no permission to change this resource.
Team member endpoints
---------------------
.. http:get:: /api/v1/organizers/(organizer)/teams/(team)/members/
Returns a list of all members of a team.
**Example request**:
.. sourcecode:: http
GET /api/v1/organizers/bigevents/teams/1/members/ HTTP/1.1
Host: pretix.eu
Accept: application/json, text/javascript
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Vary: Accept
Content-Type: application/json
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": 1,
"fullname": "John Doe",
"email": "john@example.com",
"require_2fa": true
}
]
}
:query integer page: The page number in case of a multi-page result set, default is 1
:param organizer: The ``slug`` field of the organizer to fetch
:param team: The ``id`` field of the team to fetch
:statuscode 200: no error
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer does not exist **or** you have no permission to view this resource.
:statuscode 404: The requested team does not exist
.. http:get:: /api/v1/organizers/(organizer)/teams/(team)/members/(id)/
Returns information on one team member, identified by their ID.
**Example request**:
.. sourcecode:: http
GET /api/v1/organizers/bigevents/teams/1/members/1/ HTTP/1.1
Host: pretix.eu
Accept: application/json, text/javascript
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Vary: Accept
Content-Type: application/json
{
"id": 1,
"fullname": "John Doe",
"email": "john@example.com",
"require_2fa": true
}
:param organizer: The ``slug`` field of the organizer to fetch
:param team: The ``id`` field of the team to fetch
:param id: The ``id`` field of the member to fetch
:statuscode 200: no error
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer does not exist **or** you have no permission to view this resource.
:statuscode 404: The requested team or member does not exist
.. http:delete:: /api/v1/organizers/(organizer)/teams/(team)/members/(id)/
Removes a member from the team.
**Example request**:
.. sourcecode:: http
DELETE /api/v1/organizers/bigevents/teams/1/members/1/ HTTP/1.1
Host: pretix.eu
**Example response**:
.. sourcecode:: http
HTTP/1.1 204 No Content
:param organizer: The ``slug`` field of the organizer to modify
:param team: The ``id`` field of the team to modify
:param id: The ``id`` field of the member to delete
:statuscode 204: no error
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer does not exist **or** you have no permission to create this resource.
:statuscode 404: The requested team or member does not exist
Team invite endpoints
---------------------
.. http:get:: /api/v1/organizers/(organizer)/teams/(team)/invites/
Returns a list of all invitations to a team.
**Example request**:
.. sourcecode:: http
GET /api/v1/organizers/bigevents/teams/1/invites/ HTTP/1.1
Host: pretix.eu
Accept: application/json, text/javascript
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Vary: Accept
Content-Type: application/json
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": 1,
"email": "john@example.com"
}
]
}
:query integer page: The page number in case of a multi-page result set, default is 1
:param organizer: The ``slug`` field of the organizer to fetch
:param team: The ``id`` field of the team to fetch
:statuscode 200: no error
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer does not exist **or** you have no permission to view this resource.
:statuscode 404: The requested team does not exist
.. http:get:: /api/v1/organizers/(organizer)/teams/(team)/invites/(id)/
Returns information on one invite, identified by its ID.
**Example request**:
.. sourcecode:: http
GET /api/v1/organizers/bigevents/teams/1/invites/1/ HTTP/1.1
Host: pretix.eu
Accept: application/json, text/javascript
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Vary: Accept
Content-Type: application/json
{
"id": 1,
"email": "john@example.org"
}
:param organizer: The ``slug`` field of the organizer to fetch
:param team: The ``id`` field of the team to fetch
:param id: The ``id`` field of the invite to fetch
:statuscode 200: no error
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer does not exist **or** you have no permission to view this resource.
:statuscode 404: The requested team or invite does not exist
.. http:post:: /api/v1/organizers/(organizer)/teams/(team)/invites/
Invites someone into the team. Note that if the user already has a pretix account, you will receive a response without
an ``id`` and instead of an invite being created, the user will be directly added to the team.
**Example request**:
.. sourcecode:: http
POST /api/v1/organizers/bigevents/teams/1/invites/ HTTP/1.1
Host: pretix.eu
Accept: application/json, text/javascript
Content-Type: application/json
Content-Length: 94
{
"email": "mark@example.org"
}
**Example response**:
.. sourcecode:: http
HTTP/1.1 201 Created
Vary: Accept
Content-Type: application/json
{
"id": 1,
"email": "mark@example.org"
}
:param organizer: The ``slug`` field of the organizer to modify
:param team: The ``id`` field of the team to modify
:statuscode 204: no error
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer does not exist **or** you have no permission to create this resource.
:statuscode 404: The requested team does not exist
.. http:delete:: /api/v1/organizers/(organizer)/teams/(team)/invites/(id)/
Revokes an invite.
**Example request**:
.. sourcecode:: http
DELETE /api/v1/organizers/bigevents/teams/1/invites/1/ HTTP/1.1
Host: pretix.eu
**Example response**:
.. sourcecode:: http
HTTP/1.1 204 No Content
:param organizer: The ``slug`` field of the organizer to modify
:param team: The ``id`` field of the team to modify
:param id: The ``id`` field of the invite to delete
:statuscode 204: no error
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer does not exist **or** you have no permission to create this resource.
:statuscode 404: The requested team or invite does not exist
Team API token endpoints
------------------------
.. http:get:: /api/v1/organizers/(organizer)/teams/(team)/tokens/
Returns a list of all API tokens of a team.
**Example request**:
.. sourcecode:: http
GET /api/v1/organizers/bigevents/teams/1/tokens/ HTTP/1.1
Host: pretix.eu
Accept: application/json, text/javascript
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Vary: Accept
Content-Type: application/json
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": 1,
"active": true,
"name": "Test token"
}
]
}
:query integer page: The page number in case of a multi-page result set, default is 1
:param organizer: The ``slug`` field of the organizer to fetch
:param team: The ``id`` field of the team to fetch
:statuscode 200: no error
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer does not exist **or** you have no permission to view this resource.
:statuscode 404: The requested team does not exist
.. http:get:: /api/v1/organizers/(organizer)/teams/(team)/tokens/(id)/
Returns information on one token, identified by its ID.
**Example request**:
.. sourcecode:: http
GET /api/v1/organizers/bigevents/teams/1/tokens/1/ HTTP/1.1
Host: pretix.eu
Accept: application/json, text/javascript
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Vary: Accept
Content-Type: application/json
{
"id": 1,
"active": true,
"name": "Test token"
}
:param organizer: The ``slug`` field of the organizer to fetch
:param team: The ``id`` field of the team to fetch
:param id: The ``id`` field of the token to fetch
:statuscode 200: no error
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer does not exist **or** you have no permission to view this resource.
:statuscode 404: The requested team or token does not exist
.. http:post:: /api/v1/organizers/(organizer)/teams/(team)/tokens/
Creates a new token.
**Example request**:
.. sourcecode:: http
POST /api/v1/organizers/bigevents/teams/1/tokens/ HTTP/1.1
Host: pretix.eu
Accept: application/json, text/javascript
Content-Type: application/json
Content-Length: 94
{
"name": "New token"
}
**Example response**:
.. sourcecode:: http
HTTP/1.1 201 Created
Vary: Accept
Content-Type: application/json
{
"id": 2,
"name": "New token",
"active": true,
"token": "",
}
:param organizer: The ``slug`` field of the organizer to modify
:param team: The ``id`` field of the team to create a token for
:statuscode 204: no error
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer does not exist **or** you have no permission to create this resource.
:statuscode 404: The requested team does not exist
.. http:delete:: /api/v1/organizers/(organizer)/teams/(team)/tokens/(id)/
Disables a token.
**Example request**:
.. sourcecode:: http
DELETE /api/v1/organizers/bigevents/teams/1/tokens/1/ HTTP/1.1
Host: pretix.eu
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Vary: Accept
Content-Type: application/json
{
"id": 1,
"name": "My token",
"active": false
}
:param organizer: The ``slug`` field of the organizer to modify
:param team: The ``id`` field of the team to modify
:param id: The ``id`` field of the token to delete
:statuscode 200: no error
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer does not exist **or** you have no permission to create this resource.
:statuscode 404: The requested team or token does not exist

View File

@@ -22,11 +22,18 @@ There are multiple signals that will be sent out in the ordering cycle:
.. automodule:: pretix.base.signals
:members: validate_cart, validate_cart_addons, validate_order, order_fee_calculation, order_paid, order_placed, order_canceled, order_expired, order_modified, order_changed, order_approved, order_denied, order_fee_type_name, allow_ticket_download, order_split, order_gracefully_delete, invoice_line_text
Check-ins
"""""""""
.. automodule:: pretix.base.signals
:members: checkin_created
Frontend
--------
.. automodule:: pretix.presale.signals
:members: html_head, html_footer, footer_link, front_page_top, front_page_bottom, fee_calculation_for_cart, contact_form_fields, question_form_fields, checkout_confirm_messages, checkout_confirm_page_content, checkout_all_optional, html_page_header, sass_preamble, sass_postamble, render_seating_plan, checkout_flow_steps, position_info, item_description
:members: html_head, html_footer, footer_link, front_page_top, front_page_bottom, front_page_bottom_widget, fee_calculation_for_cart, contact_form_fields, question_form_fields, checkout_confirm_messages, checkout_confirm_page_content, checkout_all_optional, html_page_header, sass_preamble, sass_postamble, render_seating_plan, checkout_flow_steps, position_info, item_description
.. automodule:: pretix.presale.signals
@@ -81,3 +88,9 @@ Ticket designs
.. automodule:: pretix.plugins.ticketoutputpdf.signals
:members: override_layout
API
---
.. automodule:: pretix.base.signals
:members: validate_event_settings, api_event_settings_fields

View File

@@ -0,0 +1,112 @@
.. highlight:: python
:linenothreshold: 5
.. _`importcol`:
Extending the order import process
==================================
It's possible through the backend to import orders into pretix, for example from a legacy ticketing system. If your
plugins defines additional data structures around orders, it might be useful to make it possible to import them as well.
Import process
--------------
Here's a short description of pretix' import process to show you where the system will need to interact with your plugin.
You can find more detailed descriptions of the attributes and methods further below.
1. The user uploads a CSV file. The system tries to parse the CSV file and understand its column headers.
2. A preview of the file is shown to the user and the user is asked to assign the various different input parameters to
columns of the file or static values. For example, the user either needs to manually select a product or specify a
column that contains a product. For this purpose, a select field is rendered for every possible input column,
allowing the user to choose between a default/empty value (defined by your ``default_value``/``default_label``)
attributes, the columns of the uploaded file, or a static value (defined by your ``static_choices`` method).
3. The user submits its assignment and the system uses the ``resolve`` method of all columns to get the raw value for
all columns.
4. The system uses the ``clean`` method of all columns to verify that all input fields are valid and transformed to the
correct data type.
5. The system prepares internal model objects (``Order`` etc) and uses the ``assign`` method of all columns to assign
these objects with actual values.
6. The system saves all of these model objects to the database in a database transaction. Plugins can create additional
objects in this stage through their ``save`` method.
Column registration
-------------------
The import API does not make a lot of usage from signals, however, it
does use a signal to get a list of all available import columns. Your plugin
should listen for this signal and return the subclass of ``pretix.base.orderimport.ImportColumn``
that we'll provide in this plugin:
.. sourcecode:: python
from django.dispatch import receiver
from pretix.base.signals import order_import_columns
@receiver(order_import_columns, dispatch_uid="custom_columns")
def register_column(sender, **kwargs):
return [
EmailColumn(sender),
]
The column class API
--------------------
.. class:: pretix.base.orderimport.ImportColumn
The central object of each import extension is the subclass of ``ImportColumn``.
.. py:attribute:: ImportColumn.event
The default constructor sets this property to the event we are currently
working for.
.. autoattribute:: identifier
This is an abstract attribute, you **must** override this!
.. autoattribute:: verbose_name
This is an abstract attribute, you **must** override this!
.. autoattribute:: default_value
.. autoattribute:: default_label
.. autoattribute:: initial
.. automethod:: static_choices
.. automethod:: resolve
.. automethod:: clean
.. automethod:: assign
.. automethod:: save
Example
-------
For example, the import column responsible for assigning email addresses looks like this:
.. sourcecode:: python
class EmailColumn(ImportColumn):
identifier = 'email'
verbose_name = _('E-mail address')
def clean(self, value, previous_values):
if value:
EmailValidator()(value)
return value
def assign(self, value, order, position, invoice_address, **kwargs):
order.email = value

View File

@@ -15,6 +15,7 @@ Contents:
placeholder
invoice
shredder
import
customview
auth
general

View File

@@ -114,6 +114,8 @@ The provider class
.. automethod:: api_payment_details
.. automethod:: matching_id
.. automethod:: shred_payment_info
.. automethod:: cancel_payment

View File

@@ -46,6 +46,9 @@ name string The human-readable name of your plugin
author string Your name
version string A human-readable version code of your plugin
description string A more verbose description of what your plugin does.
category string Category of a plugin. Either one of ``"FEATURE"``, ``"PAYMENT"``,
``"INTEGRATION"``, ``"CUSTOMIZATION"``, ``"FORMAT"``, or ``"API"``,
or any other string.
visible boolean (optional) ``True`` by default, can hide a plugin so it cannot be normally activated.
restricted boolean (optional) ``False`` by default, restricts a plugin such that it can only be enabled
for an event by system administrators / superusers.
@@ -69,6 +72,7 @@ A working example would be::
name = _("PayPal")
author = _("the pretix team")
version = '1.0.0'
category = 'PAYMENT
visible = True
restricted = False
description = _("This plugin allows you to receive payments via PayPal")

224
doc/plugins/campaigns.rst Normal file
View File

@@ -0,0 +1,224 @@
Campaigns
=========
The campaigns plugin provides a HTTP API that allows you to create new campaigns.
Resource description
--------------------
The campaign resource contains the following public fields:
.. rst-class:: rest-resource-table
===================================== ========================== =======================================================
Field Type Description
===================================== ========================== =======================================================
id integer Internal campaign ID
code string The URL component of the campaign, e.g. with code ``BAR``
the campaign URL would to be ``https://<server>/<organizer>/<event>/c/BAR/``.
This value needs to be *globally unique* and we do not
recommend setting it manually. If you omit it, a random
value will be chosen.
description string An internal, human-readable name of the campaign.
external_target string An URL to redirect to from the tracking link. To redirect to
the ticket shop, use an empty string.
order_count integer Number of orders tracked on this campaign (read-only)
click_count integer Number of clicks tracked on this campaign (read-only)
===================================== ========================== =======================================================
Endpoints
---------
.. http:get:: /api/v1/organizers/(organizer)/events/(event)/campaigns/
Returns a list of all campaigns configured for an event.
**Example request**:
.. sourcecode:: http
GET /api/v1/organizers/bigevents/events/sampleconf/campaigns/ HTTP/1.1
Host: pretix.eu
Accept: application/json, text/javascript
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Vary: Accept
Content-Type: application/json
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": 1,
"code": "wZnL11fjq",
"description": "Facebook",
"external_target": "",
"order_count:" 0,
"click_count:" 0
}
]
}
:query page: The page number in case of a multi-page result set, default is 1
:param organizer: The ``slug`` field of a valid organizer
:param event: The ``slug`` field of the event to fetch
:statuscode 200: no error
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer or event does not exist **or** you have no permission to view it.
.. http:get:: /api/v1/organizers/(organizer)/events/(event)/campaigns/(id)/
Returns information on one campaign, identified by its ID.
**Example request**:
.. sourcecode:: http
GET /api/v1/organizers/bigevents/events/sampleconf/campaigns/1/ HTTP/1.1
Host: pretix.eu
Accept: application/json, text/javascript
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Vary: Accept
Content-Type: application/json
{
"id": 1,
"code": "wZnL11fjq",
"description": "Facebook",
"external_target": "",
"order_count:" 0,
"click_count:" 0
}
:param organizer: The ``slug`` field of the organizer to fetch
:param event: The ``slug`` field of the event to fetch
:param id: The ``id`` field of the campaign to fetch
:statuscode 200: no error
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer/event/campaign does not exist **or** you have no permission to view it.
.. http:post:: /api/v1/organizers/(organizer)/events/(event)/campaigns/
Create a new campaign.
**Example request**:
.. sourcecode:: http
POST /api/v1/organizers/bigevents/events/sampleconf/campaigns/ HTTP/1.1
Host: pretix.eu
Accept: application/json, text/javascript
Content-Type: application/json
Content-Length: 166
{
"description": "Twitter"
}
**Example response**:
.. sourcecode:: http
HTTP/1.1 201 Created
Vary: Accept
Content-Type: application/json
{
"id": 2,
"code": "IfVJQzSBL",
"description": "Twitter",
"external_target": "",
"order_count:" 0,
"click_count:" 0
}
:param organizer: The ``slug`` field of the organizer to create a campaign for
:param event: The ``slug`` field of the event to create a campaign for
:statuscode 201: no error
:statuscode 400: The campaign could not be created due to invalid submitted data.
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer/event does not exist **or** you have no permission to create campaigns.
.. http:patch:: /api/v1/organizers/(organizer)/events/(event)/campaigns/(id)/
Update a campaign. You can also use ``PUT`` instead of ``PATCH``. With ``PUT``, you have to provide all fields of
the resource, other fields will be reset to default. With ``PATCH``, you only need to provide the fields that you
want to change.
**Example request**:
.. sourcecode:: http
PATCH /api/v1/organizers/bigevents/events/sampleconf/campaigns/1/ HTTP/1.1
Host: pretix.eu
Accept: application/json, text/javascript
Content-Type: application/json
Content-Length: 34
{
"external_target": "https://mywebsite.com"
}
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Vary: Accept
Content-Type: text/javascript
{
"id": 2,
"code": "IfVJQzSBL",
"description": "Twitter",
"external_target": "https://mywebsite.com",
"order_count:" 0,
"click_count:" 0
}
:param organizer: The ``slug`` field of the organizer to modify
:param event: The ``slug`` field of the event to modify
:param id: The ``id`` field of the campaign to modify
:statuscode 200: no error
:statuscode 400: The campaign could not be modified due to invalid submitted data.
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer/event/campaign does not exist **or** you have no permission to change it.
.. http:delete:: /api/v1/organizers/(organizer)/events/(event)/campaigns/(id)/
Delete a campaign and all associated data.
**Example request**:
.. sourcecode:: http
DELETE /api/v1/organizers/bigevents/events/sampleconf/campaigns/1/ HTTP/1.1
Host: pretix.eu
Accept: application/json, text/javascript
**Example response**:
.. sourcecode:: http
HTTP/1.1 204 No Content
Vary: Accept
:param organizer: The ``slug`` field of the organizer to modify
:param event: The ``slug`` field of the event to modify
:param id: The ``id`` field of the campaign to delete
:statuscode 204: no error
:statuscode 401: Authentication failure
:statuscode 403: The requested organizer/event/campaign does not exist **or** you have no permission to change it

View File

@@ -14,3 +14,4 @@ If you want to **create** a plugin, please go to the
banktransfer
ticketoutputpdf
badges
campaigns

View File

@@ -1,8 +1,9 @@
-r ../src/requirements.txt
sphinx==1.6.*
sphinx==2.3.*
sphinx-rtd-theme
sphinxcontrib-httpdomain
sphinxcontrib-images
sphinxcontrib-spelling
pygments-markdown-lexer
# See https://github.com/rfk/pyenchant/pull/130
git+https://github.com/raphaelm/pyenchant.git@patch-1#egg=pyenchant

View File

@@ -103,6 +103,7 @@ regex
renderer
renderers
reportlab
reseller
SaaS
scalability
screenshot
@@ -110,9 +111,10 @@ scss
searchable
selectable
serializable
serializers
serializer
serializers
sexualized
SQL
startup
stdout
stylesheet
@@ -139,6 +141,7 @@ untrusted
uptime
username
url
validator
versa
versioning
viewable

View File

@@ -183,6 +183,24 @@ Just as the widget, the button supports the optional attributes ``voucher`` and
You can style the button using the ``pretix-button`` CSS class.
Dynamically opening the widget
------------------------------
You can get the behavior of the pretix Button without a button at all, so you can trigger it from your own code in
response to a user action. Usually, this will open an overlay with your ticket shop, however in some cases, such as
missing HTTPS encryption on your case or a really small screen (mobile), it will open a new tab instead of an overlay.
Therefore, make sure you call this *in direct response to a user action*, otherwise most browser will block it as an
unwanted pop-up.
.. js:function:: window.PretixWidget.open(target_url [, voucher [, subevent [, items, [, widget_data [, skip_ssl_check ]]]]])
:param string target_url: The URL of the ticket shop.
:param string voucher: A voucher code to be pre-selected, or ``null``.
:param string subevent: A subevent to be pre-selected, or ``null``.
:param array items: A collection of items to be put in the cart, of the form ``[{"item": "item_3", "count": 1}, {"item": "variation_5_6", "count": 4}]``
:param object widget_data: Additional data to be passed to the shop, see below.
:param boolean skip_ssl_check: Whether to ignore the check for HTTPS. Only to be used during development.
Dynamically loading the widget
------------------------------
@@ -238,7 +256,8 @@ with that information::
data-question-L9G8NG9M="Foobar">
</pretix-widget>
This works for the pretix Button as well. Currently, the following attributes are understood by pretix itself:
This works for the pretix Button as well, if you also specify a product.
Currently, the following attributes are understood by pretix itself:
* ``data-email`` will pre-fill the order email field as well as the attendee email field (if enabled).
@@ -303,4 +322,8 @@ Hosted or pretix Enterprise are active, you can pass the following fields:
Data passing options have been added in pretix 2.3. If you use a self-hosted version of pretix, they only work
fully if you configured a redis server.
.. versionchanged:: 3.6
Dynamically opening the widget has been added in pretix 3.6.
.. _Let's Encrypt: https://letsencrypt.org/

View File

@@ -40,6 +40,24 @@ If you created a product and it doesn't show up, please follow the following ste
6. If the sale period has not started yet or is already over, check the "Show items outside presale period" setting of
your event.
Can I have different payment deadlines for different payment methods?
---------------------------------------------------------------------
No. We do not think it makes a lot of sense, for a number of reasons. First of all we believe it is not very
customer-friendly. You might for example want to configure a 1-day deadline for credit card payments and 2 weeks for
bank transfers. However, think for example of a customer who wants to pay by card and then the payment fails because
the bank locked the card or refused the payment. The customer now needs to worry about not getting their ticket, or
needs to create a new order with a different payment method. A payment deadline is a guarantee to your customer to hold
the ticket if it is paid for within a certain time frame. If you give a two-week guarantee to some of your customers,
why not to others?
There are some other issues with it as well. pretix allows customers to switch payment methods as long as their payment
has not been started or if it has failed. For example, a customer who selected bank transfer can later switch to credit
card if they haven't sent the money yet, or a customer with a failed credit card payment can switch to a different
method without creating a new order. If payment deadlines were dependent on the payment method, switching back and
forth could either allow someone to extend their deadline forever, or render someones order invalid by moving the date
back in the past.
How can I revert a check-in?
----------------------------

View File

@@ -1 +1 @@
__version__ = "3.4.0"
__version__ = "3.6.0"

View File

@@ -30,11 +30,12 @@ class CartPositionCreateSerializer(I18nAwareModelSerializer):
expires = serializers.DateTimeField(required=False)
attendee_name = serializers.CharField(required=False, allow_null=True)
seat = serializers.CharField(required=False, allow_null=True)
sales_channel = serializers.CharField(required=False, default='sales_channel')
class Meta:
model = CartPosition
fields = ('cart_id', 'item', 'variation', 'price', 'attendee_name', 'attendee_name_parts', 'attendee_email',
'subevent', 'expires', 'includes_tax', 'answers', 'seat')
'subevent', 'expires', 'includes_tax', 'answers', 'seat', 'sales_channel')
def create(self, validated_data):
answers_data = validated_data.pop('answers')
@@ -86,11 +87,12 @@ class CartPositionCreateSerializer(I18nAwareModelSerializer):
raise ValidationError('The specified seat ID is not unique.')
else:
validated_data['seat'] = seat
if not seat.is_available():
if not seat.is_available(sales_channel=validated_data.get('sales_channel', 'web')):
raise ValidationError(ugettext_lazy('The selected seat "{seat}" is not available.').format(seat=seat.name))
elif seated:
raise ValidationError('The specified product requires to choose a seat.')
validated_data.pop('sales_channel')
cp = CartPosition.objects.create(event=self.context['event'], **validated_data)
for answ_data in answers_data:

View File

@@ -4,7 +4,10 @@ from django.db import transaction
from django.utils.functional import cached_property
from django.utils.translation import ugettext as _
from django_countries.serializers import CountryFieldMixin
from rest_framework.fields import Field
from hierarkey.proxy import HierarkeyProxy
from pytz import common_timezones
from rest_framework import serializers
from rest_framework.fields import ChoiceField, Field
from rest_framework.relations import SlugRelatedField
from pretix.api.serializers.i18n import I18nAwareModelSerializer
@@ -14,6 +17,8 @@ from pretix.base.models.items import SubEventItem, SubEventItemVariation
from pretix.base.services.seating import (
SeatProtected, generate_seats, validate_plan_change,
)
from pretix.base.settings import DEFAULTS, validate_settings
from pretix.base.signals import api_event_settings_fields
class MetaDataField(Field):
@@ -61,17 +66,27 @@ class PluginsField(Field):
}
class TimeZoneField(ChoiceField):
def get_attribute(self, instance):
return instance.cache.get_or_set(
'timezone_name',
lambda: instance.settings.timezone,
3600
)
class EventSerializer(I18nAwareModelSerializer):
meta_data = MetaDataField(required=False, source='*')
plugins = PluginsField(required=False, source='*')
seat_category_mapping = SeatCategoryMappingField(source='*', required=False)
timezone = TimeZoneField(required=False, choices=[(a, a) for a in common_timezones])
class Meta:
model = Event
fields = ('name', 'slug', 'live', 'testmode', 'currency', 'date_from',
'date_to', 'date_admission', 'is_public', 'presale_start',
'presale_end', 'location', 'geo_lat', 'geo_lon', 'has_subevents', 'meta_data', 'seating_plan',
'plugins', 'seat_category_mapping')
'plugins', 'seat_category_mapping', 'timezone')
def validate(self, data):
data = super().validate(data)
@@ -127,8 +142,11 @@ class EventSerializer(I18nAwareModelSerializer):
return value
def validate_seat_category_mapping(self, value):
if value and value['seat_category_mapping'] and (not self.instance or not self.instance.pk):
raise ValidationError('You cannot specify seat category mappings on event creation.')
if not self.instance or not self.instance.pk:
if value and value['seat_category_mapping']:
raise ValidationError('You cannot specify seat category mappings on event creation.')
else:
return {'seat_category_mapping': {}}
item_cache = {i.pk: i for i in self.instance.items.all()}
result = {}
for k, item in value['seat_category_mapping'].items():
@@ -156,8 +174,12 @@ class EventSerializer(I18nAwareModelSerializer):
meta_data = validated_data.pop('meta_data', None)
validated_data.pop('seat_category_mapping', None)
plugins = validated_data.pop('plugins', settings.PRETIX_PLUGINS_DEFAULT.split(','))
tz = validated_data.pop('timezone', None)
event = super().create(validated_data)
if tz:
event.settings.timezone = tz
# Meta data
if meta_data is not None:
for key, value in meta_data.items():
@@ -182,8 +204,12 @@ class EventSerializer(I18nAwareModelSerializer):
meta_data = validated_data.pop('meta_data', None)
plugins = validated_data.pop('plugins', None)
seat_category_mapping = validated_data.pop('seat_category_mapping', None)
tz = validated_data.pop('timezone', None)
event = super().update(instance, validated_data)
if tz:
event.settings.timezone = tz
# Meta data
if meta_data is not None:
current = {mv.property: mv for mv in event.meta_values.select_related('property')}
@@ -240,6 +266,7 @@ class CloneEventSerializer(EventSerializer):
is_public = validated_data.pop('is_public', None)
testmode = validated_data.pop('testmode', None)
has_subevents = validated_data.pop('has_subevents', None)
tz = validated_data.pop('timezone', None)
new_event = super().create(validated_data)
event = Event.objects.filter(slug=self.context['event'], organizer=self.context['organizer'].pk).first()
@@ -254,6 +281,8 @@ class CloneEventSerializer(EventSerializer):
if has_subevents is not None:
new_event.has_subevents = has_subevents
new_event.save()
if tz:
new_event.settings.timezone = tz
return new_event
@@ -444,3 +473,126 @@ class TaxRuleSerializer(CountryFieldMixin, I18nAwareModelSerializer):
class Meta:
model = TaxRule
fields = ('id', 'name', 'rate', 'price_includes_tax', 'eu_reverse_charge', 'home_country')
class EventSettingsSerializer(serializers.Serializer):
default_fields = [
'imprint_url',
'checkout_email_helptext',
'presale_has_ended_text',
'voucher_explanation_text',
'show_date_to',
'show_times',
'show_items_outside_presale_period',
'display_net_prices',
'presale_start_show_date',
'locales',
'locale',
'last_order_modification_date',
'show_quota_left',
'waiting_list_enabled',
'waiting_list_hours',
'waiting_list_auto',
'max_items_per_order',
'reservation_time',
'contact_mail',
'show_variations_expanded',
'hide_sold_out',
'meta_noindex',
'redirect_to_checkout_directly',
'frontpage_subevent_ordering',
'frontpage_text',
'attendee_names_asked',
'attendee_names_required',
'attendee_emails_asked',
'attendee_emails_required',
'confirm_text',
'order_email_asked_twice',
'payment_term_days',
'payment_term_last',
'payment_term_weekdays',
'payment_term_expire_automatically',
'payment_term_accept_late',
'payment_explanation',
'ticket_download',
'ticket_download_date',
'ticket_download_addons',
'ticket_download_nonadm',
'ticket_download_pending',
'mail_prefix',
'mail_from',
'mail_from_name',
'mail_attach_ical',
'invoice_address_asked',
'invoice_address_required',
'invoice_address_vatid',
'invoice_address_company_required',
'invoice_address_beneficiary',
'invoice_name_required',
'invoice_address_not_asked_free',
'invoice_show_payments',
'invoice_reissue_after_modify',
'invoice_include_free',
'invoice_generate',
'invoice_numbers_consecutive',
'invoice_numbers_prefix',
'invoice_numbers_prefix_cancellations',
'invoice_attendee_name',
'invoice_include_expire_date',
'invoice_address_explanation_text',
'invoice_email_attachment',
'invoice_address_from_name',
'invoice_address_from',
'invoice_address_from_zipcode',
'invoice_address_from_city',
'invoice_address_from_country',
'invoice_address_from_tax_id',
'invoice_address_from_vat_id',
'invoice_introductory_text',
'invoice_additional_text',
'invoice_footer_text',
'cancel_allow_user',
'cancel_allow_user_until',
'cancel_allow_user_paid',
'cancel_allow_user_paid_until',
'cancel_allow_user_paid_keep',
'cancel_allow_user_paid_keep_fees',
'cancel_allow_user_paid_keep_percentage',
]
def __init__(self, *args, **kwargs):
self.event = kwargs.pop('event')
super().__init__(*args, **kwargs)
for fname in self.default_fields:
kwargs = DEFAULTS[fname].get('serializer_kwargs', {})
kwargs.setdefault('required', False)
kwargs.setdefault('allow_null', True)
form_kwargs = DEFAULTS[fname].get('form_kwargs', {})
if 'serializer_class' not in DEFAULTS[fname]:
raise ValidationError('{} has no serializer class'.format(fname))
f = DEFAULTS[fname]['serializer_class'](
**kwargs
)
f._label = form_kwargs.get('label', fname)
f._help_text = form_kwargs.get('help_text')
self.fields[fname] = f
for recv, resp in api_event_settings_fields.send(sender=self.event):
for fname, field in resp.items():
field.required = False
self.fields[fname] = field
def update(self, instance: HierarkeyProxy, validated_data):
for attr, value in validated_data.items():
if value is None:
instance.delete(attr)
elif instance.get(attr, as_type=type(value)) != value:
instance.set(attr, value)
return instance
def validate(self, data):
data = super().validate(data)
settings_dict = self.instance.freeze()
settings_dict.update(data)
validate_settings(self.event, settings_dict)
return data

View File

@@ -227,7 +227,7 @@ class QuestionSerializer(I18nAwareModelSerializer):
model = Question
fields = ('id', 'question', 'type', 'required', 'items', 'options', 'position',
'ask_during_checkin', 'identifier', 'dependency_question', 'dependency_values',
'hidden', 'dependency_value', 'print_on_invoice')
'hidden', 'dependency_value', 'print_on_invoice', 'help_text')
def validate_identifier(self, value):
Question._clean_identifier(self.context['event'], value, self.instance)

View File

@@ -204,7 +204,7 @@ class OrderPositionSerializer(I18nAwareModelSerializer):
model = OrderPosition
fields = ('id', 'order', 'positionid', 'item', 'variation', 'price', 'attendee_name', 'attendee_name_parts',
'attendee_email', 'voucher', 'tax_rate', 'tax_value', 'secret', 'addon_to', 'subevent', 'checkins',
'downloads', 'answers', 'tax_rule', 'pseudonymization_id', 'pdf_data', 'seat')
'downloads', 'answers', 'tax_rule', 'pseudonymization_id', 'pdf_data', 'seat', 'canceled')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@@ -284,7 +284,7 @@ class OrderPaymentDateField(serializers.DateField):
class OrderFeeSerializer(I18nAwareModelSerializer):
class Meta:
model = OrderFee
fields = ('fee_type', 'value', 'description', 'internal_type', 'tax_rate', 'tax_value', 'tax_rule')
fields = ('fee_type', 'value', 'description', 'internal_type', 'tax_rate', 'tax_value', 'tax_rule', 'canceled')
class PaymentURLField(serializers.URLField):
@@ -720,6 +720,7 @@ class OrderCreateSerializer(I18nAwareModelSerializer):
consume_carts = validated_data.pop('consume_carts', [])
delete_cps = []
quota_avail_cache = {}
v_budget = {}
voucher_usage = Counter()
if consume_carts:
for cp in CartPosition.objects.filter(
@@ -742,9 +743,14 @@ class OrderCreateSerializer(I18nAwareModelSerializer):
errs = [{} for p in positions_data]
for i, pos_data in enumerate(positions_data):
if pos_data.get('voucher'):
v = pos_data['voucher']
if pos_data.get('addon_to'):
errs[i]['voucher'] = ['Vouchers are currently not supported for add-on products.']
continue
if not v.applies_to(pos_data['item'], pos_data.get('variation')):
errs[i]['voucher'] = [error_messages['voucher_invalid_item']]
continue
@@ -768,6 +774,44 @@ class OrderCreateSerializer(I18nAwareModelSerializer):
'The voucher has already been used the maximum number of times.'
]
if v.budget is not None:
price = pos_data.get('price')
if price is None:
price = get_price(
item=pos_data.get('item'),
variation=pos_data.get('variation'),
voucher=v,
custom_price=None,
subevent=pos_data.get('subevent'),
addon_to=pos_data.get('addon_to'),
invoice_address=ia,
).gross
pbv = get_price(
item=pos_data['item'],
variation=pos_data.get('variation'),
voucher=None,
custom_price=None,
subevent=pos_data.get('subevent'),
addon_to=pos_data.get('addon_to'),
invoice_address=ia,
)
if v not in v_budget:
v_budget[v] = v.budget - v.budget_used()
disc = pbv.gross - price
if disc > v_budget[v]:
new_disc = v_budget[v]
v_budget[v] -= new_disc
if new_disc == Decimal('0.00') or pos_data.get('price') is not None:
errs[i]['voucher'] = [
'The voucher has a remaining budget of {}, therefore a discount of {} can not be '
'given.'.format(v_budget[v] + new_disc, disc)
]
continue
pos_data['price'] = price + (disc - new_disc)
else:
v_budget[v] -= disc
seated = pos_data.get('item').seat_category_mappings.filter(subevent=pos_data.get('subevent')).exists()
if pos_data.get('seat'):
if not seated:
@@ -778,7 +822,7 @@ class OrderCreateSerializer(I18nAwareModelSerializer):
errs[i]['seat'] = ['The specified seat does not exist.']
else:
pos_data['seat'] = seat
if (seat not in free_seats and not seat.is_available()) or seat in seats_seen:
if (seat not in free_seats and not seat.is_available(sales_channel=validated_data.get('sales_channel', 'web'))) or seat in seats_seen:
errs[i]['seat'] = [ugettext_lazy('The selected seat "{seat}" is not available.').format(seat=seat.name)]
seats_seen.add(seat)
elif seated:
@@ -856,6 +900,17 @@ class OrderCreateSerializer(I18nAwareModelSerializer):
pos.tax_rule = pos.item.tax_rule
else:
pos._calculate_tax()
pos.price_before_voucher = get_price(
item=pos.item,
variation=pos.variation,
voucher=None,
custom_price=None,
subevent=pos.subevent,
addon_to=pos.addon_to,
invoice_address=ia,
).gross
if pos.voucher:
Voucher.objects.filter(pk=pos.voucher.pk).update(redeemed=F('redeemed') + 1)
pos.save()
@@ -979,6 +1034,20 @@ class InvoiceSerializer(I18nAwareModelSerializer):
'internal_reference')
class OrderPaymentCreateSerializer(I18nAwareModelSerializer):
provider = serializers.CharField(required=True, allow_null=False, allow_blank=False)
info = CompatibleJSONField(required=False)
class Meta:
model = OrderPayment
fields = ('state', 'amount', 'payment_date', 'provider', 'info')
def create(self, validated_data):
order = OrderPayment(order=self.context['order'], **validated_data)
order.save()
return order
class OrderRefundCreateSerializer(I18nAwareModelSerializer):
payment = serializers.IntegerField(required=False, allow_null=True)
provider = serializers.CharField(required=True, allow_null=False, allow_blank=False)

View File

@@ -1,12 +1,19 @@
from decimal import Decimal
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import get_language, ugettext_lazy as _
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from pretix.api.serializers.i18n import I18nAwareModelSerializer
from pretix.api.serializers.order import CompatibleJSONField
from pretix.base.models import GiftCard, Organizer, SeatingPlan
from pretix.base.auth import get_auth_backends
from pretix.base.models import (
GiftCard, Organizer, SeatingPlan, Team, TeamAPIToken, TeamInvite, User,
)
from pretix.base.models.seating import SeatingPlanLayoutValidator
from pretix.base.services.mail import SendMailException, mail
from pretix.helpers.urls import build_absolute_uri
class OrganizerSerializer(I18nAwareModelSerializer):
@@ -26,7 +33,7 @@ class SeatingPlanSerializer(I18nAwareModelSerializer):
class GiftCardSerializer(I18nAwareModelSerializer):
value = serializers.DecimalField(max_digits=10, decimal_places=2)
value = serializers.DecimalField(max_digits=10, decimal_places=2, min_value=Decimal('0.00'))
def validate(self, data):
data = super().validate(data)
@@ -34,16 +41,129 @@ class GiftCardSerializer(I18nAwareModelSerializer):
qs = GiftCard.objects.filter(
secret=s
).filter(
Q(issuer=self.context["organizer"]) | Q(issuer__gift_card_collector_acceptance__collector=self.context["organizer"])
Q(issuer=self.context["organizer"]) | Q(
issuer__gift_card_collector_acceptance__collector=self.context["organizer"])
)
if self.instance:
qs = qs.exclude(pk=self.instance.pk)
if qs.exists():
raise ValidationError(
{'secret': _('A gift card with the same secret already exists in your or an affiliated organizer account.')}
{'secret': _(
'A gift card with the same secret already exists in your or an affiliated organizer account.')}
)
return data
class Meta:
model = GiftCard
fields = ('id', 'secret', 'issuance', 'value', 'currency', 'testmode')
class EventSlugField(serializers.SlugRelatedField):
def get_queryset(self):
return self.context['organizer'].events.all()
class TeamSerializer(serializers.ModelSerializer):
limit_events = EventSlugField(slug_field='slug', many=True)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class Meta:
model = Team
fields = (
'id', 'name', 'all_events', 'limit_events', 'can_create_events', 'can_change_teams',
'can_change_organizer_settings', 'can_manage_gift_cards', 'can_change_event_settings',
'can_change_items', 'can_view_orders', 'can_change_orders', 'can_view_vouchers',
'can_change_vouchers'
)
def validate(self, data):
full_data = self.to_internal_value(self.to_representation(self.instance)) if self.instance else {}
full_data.update(data)
if full_data.get('limit_events') and full_data.get('all_events'):
raise ValidationError('Do not set both limit_events and all_events.')
return data
class TeamInviteSerializer(serializers.ModelSerializer):
class Meta:
model = TeamInvite
fields = (
'id', 'email'
)
def _send_invite(self, instance):
try:
mail(
instance.email,
_('pretix account invitation'),
'pretixcontrol/email/invitation.txt',
{
'user': self,
'organizer': self.context['organizer'].name,
'team': instance.team.name,
'url': build_absolute_uri('control:auth.invite', kwargs={
'token': instance.token
})
},
event=None,
locale=get_language() # TODO: expose?
)
except SendMailException:
pass # Already logged
def create(self, validated_data):
if 'email' in validated_data:
try:
user = User.objects.get(email__iexact=validated_data['email'])
except User.DoesNotExist:
if self.context['team'].invites.filter(email__iexact=validated_data['email']).exists():
raise ValidationError(_('This user already has been invited for this team.'))
if 'native' not in get_auth_backends():
raise ValidationError('Users need to have a pretix account before they can be invited.')
invite = self.context['team'].invites.create(email=validated_data['email'])
self._send_invite(invite)
invite.team.log_action(
'pretix.team.invite.created',
data={
'email': validated_data['email']
},
**self.context['log_kwargs']
)
return invite
else:
if self.context['team'].members.filter(pk=user.pk).exists():
raise ValidationError(_('This user already has permissions for this team.'))
self.context['team'].members.add(user)
self.context['team'].log_action(
'pretix.team.member.added',
data={
'email': user.email,
'user': user.pk,
},
**self.context['log_kwargs']
)
return TeamInvite(email=user.email)
else:
raise ValidationError('No email address given.')
class TeamAPITokenSerializer(serializers.ModelSerializer):
active = serializers.BooleanField(default=True, read_only=True)
class Meta:
model = TeamAPIToken
fields = (
'id', 'name', 'active'
)
class TeamMemberSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = (
'id', 'email', 'fullname', 'require_2fa'
)

View File

@@ -7,8 +7,8 @@ from rest_framework import routers
from pretix.api.views import cart
from .views import (
checkin, device, event, item, oauth, order, organizer, user, voucher,
waitinglist, webhooks,
checkin, device, event, item, oauth, order, organizer, user, version,
voucher, waitinglist, webhooks,
)
router = routers.DefaultRouter()
@@ -20,6 +20,12 @@ orga_router.register(r'subevents', event.SubEventViewSet)
orga_router.register(r'webhooks', webhooks.WebHookViewSet)
orga_router.register(r'seatingplans', organizer.SeatingPlanViewSet)
orga_router.register(r'giftcards', organizer.GiftCardViewSet)
orga_router.register(r'teams', organizer.TeamViewSet)
team_router = routers.DefaultRouter()
team_router.register(r'members', organizer.TeamMemberViewSet)
team_router.register(r'invites', organizer.TeamInviteViewSet)
team_router.register(r'tokens', organizer.TeamAPITokenViewSet)
event_router = routers.DefaultRouter()
event_router.register(r'subevents', event.SubEventViewSet)
@@ -61,7 +67,10 @@ for app in apps.get_app_configs():
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^organizers/(?P<organizer>[^/]+)/', include(orga_router.urls)),
url(r'^organizers/(?P<organizer>[^/]+)/events/(?P<event>[^/]+)/settings/$', event.EventSettingsView.as_view(),
name="event.settings"),
url(r'^organizers/(?P<organizer>[^/]+)/events/(?P<event>[^/]+)/', include(event_router.urls)),
url(r'^organizers/(?P<organizer>[^/]+)/teams/(?P<team>[^/]+)/', include(team_router.urls)),
url(r'^organizers/(?P<organizer>[^/]+)/events/(?P<event>[^/]+)/items/(?P<item>[^/]+)/', include(item_router.urls)),
url(r'^organizers/(?P<organizer>[^/]+)/events/(?P<event>[^/]+)/questions/(?P<question>[^/]+)/',
include(question_router.urls)),
@@ -76,4 +85,5 @@ urlpatterns = [
url(r"^device/roll$", device.RollKeyView.as_view(), name="device.roll"),
url(r"^device/revoke$", device.RevokeKeyView.as_view(), name="device.revoke"),
url(r"^me$", user.MeView.as_view(), name="user.me"),
url(r"^version$", version.VersionView.as_view(), name="version"),
]

View File

@@ -4,13 +4,14 @@ from django.db.models import ProtectedError, Q
from django.utils.timezone import now
from django_filters.rest_framework import DjangoFilterBackend, FilterSet
from django_scopes import scopes_disabled
from rest_framework import filters, viewsets
from rest_framework import filters, views, viewsets
from rest_framework.exceptions import PermissionDenied
from rest_framework.response import Response
from pretix.api.auth.permission import EventCRUDPermission
from pretix.api.serializers.event import (
CloneEventSerializer, EventSerializer, SubEventSerializer,
TaxRuleSerializer,
CloneEventSerializer, EventSerializer, EventSettingsSerializer,
SubEventSerializer, TaxRuleSerializer,
)
from pretix.api.views import ConditionalListView
from pretix.base.models import (
@@ -133,6 +134,7 @@ class EventViewSet(viewsets.ModelViewSet):
def perform_create(self, serializer):
serializer.save(organizer=self.request.organizer)
serializer.instance.set_defaults()
serializer.instance.log_action(
'pretix.event.added',
user=self.request.user,
@@ -332,3 +334,33 @@ class TaxRuleViewSet(ConditionalListView, viewsets.ModelViewSet):
auth=self.request.auth,
)
super().perform_destroy(instance)
class EventSettingsView(views.APIView):
permission = 'can_change_event_settings'
def get(self, request, *args, **kwargs):
s = EventSettingsSerializer(instance=request.event.settings, event=request.event)
if 'explain' in request.GET:
return Response({
fname: {
'value': s.data[fname],
'label': getattr(field, '_label', fname),
'help_text': getattr(field, '_help_text', None)
} for fname, field in s.fields.items()
})
return Response(s.data)
def patch(self, request, *wargs, **kwargs):
s = EventSettingsSerializer(instance=request.event.settings, data=request.data, partial=True,
event=request.event)
s.is_valid(raise_exception=True)
with transaction.atomic():
s.save()
self.request.event.log_action(
'pretix.event.settings', user=self.request.user, auth=self.request.auth, data={
k: v for k, v in s.validated_data.items()
}
)
s = EventSettingsSerializer(instance=request.event.settings, event=request.event)
return Response(s.data)

View File

@@ -23,15 +23,16 @@ from rest_framework.response import Response
from pretix.api.models import OAuthAccessToken
from pretix.api.serializers.order import (
InvoiceSerializer, OrderCreateSerializer, OrderPaymentSerializer,
OrderPositionSerializer, OrderRefundCreateSerializer,
OrderRefundSerializer, OrderSerializer, PriceCalcSerializer,
InvoiceSerializer, OrderCreateSerializer, OrderPaymentCreateSerializer,
OrderPaymentSerializer, OrderPositionSerializer,
OrderRefundCreateSerializer, OrderRefundSerializer, OrderSerializer,
PriceCalcSerializer,
)
from pretix.base.i18n import language
from pretix.base.models import (
CachedCombinedTicket, CachedTicket, Device, Event, Invoice, InvoiceAddress,
Order, OrderPayment, OrderPosition, OrderRefund, Quota, TeamAPIToken,
generate_position_secret, generate_secret,
Order, OrderFee, OrderPayment, OrderPosition, OrderRefund, Quota,
TeamAPIToken, generate_position_secret, generate_secret,
)
from pretix.base.payment import PaymentException
from pretix.base.services import tickets
@@ -82,20 +83,29 @@ class OrderViewSet(viewsets.ModelViewSet):
return ctx
def get_queryset(self):
if self.request.query_params.get('include_canceled_fees', 'false') == 'true':
fqs = OrderFee.all
else:
fqs = OrderFee.objects
qs = self.request.event.orders.prefetch_related(
'fees', 'payments', 'refunds', 'refunds__payment'
Prefetch('fees', queryset=fqs.all()),
'payments', 'refunds', 'refunds__payment'
).select_related(
'invoice_address'
)
if self.request.query_params.get('include_canceled_positions', 'false') == 'true':
opq = OrderPosition.all
else:
opq = OrderPosition.objects
if self.request.query_params.get('pdf_data', 'false') == 'true':
qs = qs.prefetch_related(
Prefetch(
'positions',
OrderPosition.objects.all().prefetch_related(
opq.all().prefetch_related(
'checkins', 'item', 'variation', 'answers', 'answers__options', 'answers__question',
'item__category', 'addon_to', 'seat',
Prefetch('addons', OrderPosition.objects.select_related('item', 'variation', 'seat'))
Prefetch('addons', opq.select_related('item', 'variation', 'seat'))
)
)
)
@@ -103,7 +113,7 @@ class OrderViewSet(viewsets.ModelViewSet):
qs = qs.prefetch_related(
Prefetch(
'positions',
OrderPosition.objects.all().prefetch_related(
opq.all().prefetch_related(
'checkins', 'item', 'variation', 'answers', 'answers__options', 'answers__question', 'seat',
)
)
@@ -654,11 +664,16 @@ class OrderPositionViewSet(mixins.DestroyModelMixin, viewsets.ReadOnlyModelViewS
}
def get_queryset(self):
qs = OrderPosition.objects.filter(order__event=self.request.event)
if self.request.query_params.get('include_canceled_positions', 'false') == 'true':
qs = OrderPosition.all
else:
qs = OrderPosition.objects
qs = qs.filter(order__event=self.request.event)
if self.request.query_params.get('pdf_data', 'false') == 'true':
qs = qs.prefetch_related(
'checkins', 'answers', 'answers__options', 'answers__question',
Prefetch('addons', OrderPosition.objects.select_related('item', 'variation')),
Prefetch('addons', qs.select_related('item', 'variation')),
Prefetch('order', Order.objects.select_related('invoice_address').prefetch_related(
Prefetch(
'event',
@@ -666,7 +681,7 @@ class OrderPositionViewSet(mixins.DestroyModelMixin, viewsets.ReadOnlyModelViewS
),
Prefetch(
'positions',
OrderPosition.objects.prefetch_related(
qs.prefetch_related(
'checkins', 'item', 'variation', 'answers', 'answers__options', 'answers__question',
)
)
@@ -676,7 +691,7 @@ class OrderPositionViewSet(mixins.DestroyModelMixin, viewsets.ReadOnlyModelViewS
)
else:
qs = qs.prefetch_related(
'checkins', 'answers', 'answers__options', 'answers__question'
'checkins', 'answers', 'answers__options', 'answers__question',
).select_related(
'item', 'order', 'order__event', 'order__event__organizer', 'seat'
)
@@ -811,17 +826,62 @@ class OrderPositionViewSet(mixins.DestroyModelMixin, viewsets.ReadOnlyModelViewS
raise ValidationError(str(e))
class PaymentViewSet(viewsets.ReadOnlyModelViewSet):
class PaymentViewSet(CreateModelMixin, viewsets.ReadOnlyModelViewSet):
serializer_class = OrderPaymentSerializer
queryset = OrderPayment.objects.none()
permission = 'can_view_orders'
write_permission = 'can_change_orders'
lookup_field = 'local_id'
def get_serializer_context(self):
ctx = super().get_serializer_context()
ctx['order'] = get_object_or_404(Order, code=self.kwargs['order'], event=self.request.event)
return ctx
def get_queryset(self):
order = get_object_or_404(Order, code=self.kwargs['order'], event=self.request.event)
return order.payments.all()
def create(self, request, *args, **kwargs):
serializer = OrderPaymentCreateSerializer(data=request.data, context=self.get_serializer_context())
serializer.is_valid(raise_exception=True)
with transaction.atomic():
mark_confirmed = False
if serializer.validated_data['state'] == OrderPayment.PAYMENT_STATE_CONFIRMED:
serializer.validated_data['state'] = OrderPayment.PAYMENT_STATE_PENDING
mark_confirmed = True
self.perform_create(serializer)
r = serializer.instance
if mark_confirmed:
try:
r.confirm(
user=self.request.user if self.request.user.is_authenticated else None,
auth=self.request.auth,
count_waitinglist=False,
force=request.data.get('force', False)
)
except Quota.QuotaExceededException:
pass
except SendMailException:
pass
serializer = OrderPaymentSerializer(r, context=serializer.context)
r.order.log_action(
'pretix.event.order.payment.started', {
'local_id': r.local_id,
'provider': r.provider,
},
user=request.user if request.user.is_authenticated else None,
auth=request.auth
)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
def perform_create(self, serializer):
serializer.save()
@action(detail=True, methods=['POST'])
def confirm(self, request, **kwargs):
payment = self.get_object()
@@ -1001,6 +1061,7 @@ class RefundViewSet(CreateModelMixin, viewsets.ReadOnlyModelViewSet):
mark_refunded = request.data.pop('mark_refunded', False)
else:
mark_refunded = request.data.pop('mark_canceled', False)
mark_pending = request.data.pop('mark_pending', False)
serializer = OrderRefundCreateSerializer(data=request.data, context=self.get_serializer_context())
serializer.is_valid(raise_exception=True)
with transaction.atomic():
@@ -1022,6 +1083,15 @@ class RefundViewSet(CreateModelMixin, viewsets.ReadOnlyModelViewSet):
user=request.user if request.user.is_authenticated else None,
auth=(request.auth if request.auth else None),
)
elif mark_pending:
if r.order.status == Order.STATUS_PAID and r.order.pending_sum > 0:
r.order.status = Order.STATUS_PENDING
r.order.set_expires(
now(),
r.order.event.subevents.filter(
id__in=r.order.positions.values_list('subevent_id', flat=True))
)
r.order.save(update_fields=['status', 'expires'])
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

View File

@@ -1,14 +1,23 @@
from decimal import Decimal
from django.db import transaction
from django.shortcuts import get_object_or_404
from django.utils.functional import cached_property
from rest_framework import filters, serializers, status, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import MethodNotAllowed, PermissionDenied
from rest_framework.mixins import CreateModelMixin, DestroyModelMixin
from rest_framework.response import Response
from pretix.api.models import OAuthAccessToken
from pretix.api.serializers.organizer import (
GiftCardSerializer, OrganizerSerializer, SeatingPlanSerializer,
TeamAPITokenSerializer, TeamInviteSerializer, TeamMemberSerializer,
TeamSerializer,
)
from pretix.base.models import (
GiftCard, Organizer, SeatingPlan, Team, TeamAPIToken, TeamInvite, User,
)
from pretix.base.models import GiftCard, Organizer, SeatingPlan
from pretix.helpers.dicts import merge_dicts
@@ -53,6 +62,7 @@ class SeatingPlanViewSet(viewsets.ModelViewSet):
ctx['organizer'] = self.request.organizer
return ctx
@transaction.atomic()
def perform_create(self, serializer):
inst = serializer.save(organizer=self.request.organizer)
self.request.organizer.log_action(
@@ -62,6 +72,7 @@ class SeatingPlanViewSet(viewsets.ModelViewSet):
data=merge_dicts(self.request.data, {'id': inst.pk})
)
@transaction.atomic()
def perform_update(self, serializer):
if serializer.instance.events.exists() or serializer.instance.subevents.exists():
raise PermissionDenied('This plan can not be changed while it is in use for an event.')
@@ -74,6 +85,7 @@ class SeatingPlanViewSet(viewsets.ModelViewSet):
)
return inst
@transaction.atomic()
def perform_destroy(self, instance):
if instance.events.exists() or instance.subevents.exists():
raise PermissionDenied('This plan can not be deleted while it is in use for an event.')
@@ -136,6 +148,10 @@ class GiftCardViewSet(viewsets.ModelViewSet):
value = serializers.DecimalField(max_digits=10, decimal_places=2).to_internal_value(
request.data.get('value')
)
if gc.value + value < Decimal('0.00'):
return Response({
'value': ['The gift card does not have sufficient credit for this operation.']
}, status=status.HTTP_409_CONFLICT)
gc.transactions.create(value=value)
gc.log_action(
'pretix.giftcards.transaction.manual',
@@ -147,3 +163,169 @@ class GiftCardViewSet(viewsets.ModelViewSet):
def perform_destroy(self, instance):
raise MethodNotAllowed("Gift cards cannot be deleted.")
class TeamViewSet(viewsets.ModelViewSet):
serializer_class = TeamSerializer
queryset = Team.objects.none()
permission = 'can_change_teams'
write_permission = 'can_change_teams'
def get_queryset(self):
return self.request.organizer.teams.all()
def get_serializer_context(self):
ctx = super().get_serializer_context()
ctx['organizer'] = self.request.organizer
return ctx
@transaction.atomic()
def perform_create(self, serializer):
inst = serializer.save(organizer=self.request.organizer)
inst.log_action(
'pretix.team.created',
user=self.request.user,
auth=self.request.auth,
data=merge_dicts(self.request.data, {'id': inst.pk})
)
@transaction.atomic()
def perform_update(self, serializer):
inst = serializer.save()
inst.log_action(
'pretix.team.changed',
user=self.request.user,
auth=self.request.auth,
data=self.request.data
)
return inst
def perform_destroy(self, instance):
instance.log_action('pretix.team.deleted', user=self.request.user, auth=self.request.auth)
instance.delete()
class TeamMemberViewSet(DestroyModelMixin, viewsets.ReadOnlyModelViewSet):
serializer_class = TeamMemberSerializer
queryset = User.objects.none()
permission = 'can_change_teams'
write_permission = 'can_change_teams'
@cached_property
def team(self):
return get_object_or_404(self.request.organizer.teams, pk=self.kwargs.get('team'))
def get_queryset(self):
return self.team.members.all()
def get_serializer_context(self):
ctx = super().get_serializer_context()
ctx['organizer'] = self.request.organizer
return ctx
@transaction.atomic()
def perform_destroy(self, instance):
self.team.members.remove(instance)
self.team.log_action(
'pretix.team.member.removed', user=self.request.user, auth=self.request.auth, data={
'email': instance.email,
'user': instance.pk
}
)
class TeamInviteViewSet(CreateModelMixin, DestroyModelMixin, viewsets.ReadOnlyModelViewSet):
serializer_class = TeamInviteSerializer
queryset = TeamInvite.objects.none()
permission = 'can_change_teams'
write_permission = 'can_change_teams'
@cached_property
def team(self):
return get_object_or_404(self.request.organizer.teams, pk=self.kwargs.get('team'))
def get_queryset(self):
return self.team.invites.all()
def get_serializer_context(self):
ctx = super().get_serializer_context()
ctx['organizer'] = self.request.organizer
ctx['team'] = self.team
ctx['log_kwargs'] = {
'user': self.request.user,
'auth': self.request.auth,
}
return ctx
@transaction.atomic()
def perform_destroy(self, instance):
self.team.log_action(
'pretix.team.invite.deleted', user=self.request.user, auth=self.request.auth, data={
'email': instance.email,
}
)
instance.delete()
@transaction.atomic()
def perform_create(self, serializer):
serializer.save(team=self.team)
class TeamAPITokenViewSet(CreateModelMixin, DestroyModelMixin, viewsets.ReadOnlyModelViewSet):
serializer_class = TeamAPITokenSerializer
queryset = TeamAPIToken.objects.none()
permission = 'can_change_teams'
write_permission = 'can_change_teams'
@cached_property
def team(self):
return get_object_or_404(self.request.organizer.teams, pk=self.kwargs.get('team'))
def get_queryset(self):
return self.team.tokens.all()
def get_serializer_context(self):
ctx = super().get_serializer_context()
ctx['organizer'] = self.request.organizer
ctx['team'] = self.team
ctx['log_kwargs'] = {
'user': self.request.user,
'auth': self.request.auth,
}
return ctx
@transaction.atomic()
def perform_destroy(self, instance):
instance.active = False
instance.save()
self.team.log_action(
'pretix.team.token.deleted', user=self.request.user, auth=self.request.auth, data={
'name': instance.name,
}
)
@transaction.atomic()
def perform_create(self, serializer):
instance = serializer.save(team=self.team)
self.team.log_action(
'pretix.team.token.created', auth=self.request.auth, user=self.request.user, data={
'name': instance.name,
'id': instance.pk
}
)
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
d = serializer.data
d['token'] = serializer.instance.token
return Response(d, status=status.HTTP_201_CREATED, headers=headers)
def destroy(self, request, *args, **kwargs):
instance = self.get_object()
self.perform_destroy(instance)
serializer = self.get_serializer_class()(instance)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_200_OK, headers=headers)

View File

@@ -0,0 +1,56 @@
from oauth2_provider.contrib.rest_framework import OAuth2Authentication
from packaging import version
from rest_framework.authentication import SessionAuthentication
from rest_framework.response import Response
from rest_framework.views import APIView
from pretix import __version__
from pretix.api.auth.device import DeviceTokenAuthentication
from pretix.api.auth.token import TeamTokenAuthentication
def numeric_version(v):
# Converts a pretix version to a large int
# e.g. 30060001000
# |--------------------- Major version
# |-|------------------ Minor version
# |-|--------------- Patch version
# ||------------- Stage (10 dev, 20 alpha, 30 beta, 40 rc, 50 release, 60 post)
# ||----------- Stage version (number of dev/alpha/beta/rc/post release)
v = version.parse(v)
phases = {
'dev': 10,
'a': 20,
'b': 30,
'rc': 40,
'release': 50,
'post': 60
}
vnum = 0
if v.is_postrelease:
vnum += v.post
vnum += phases['post'] * 100
elif v.dev is not None:
vnum += v.dev
vnum += phases['dev'] * 100
elif v.is_prerelease and v.pre:
vnum += v.pre[0]
vnum += phases[v.pre[1]] * 100
else:
vnum += phases['release'] * 100
for i, part in enumerate(reversed(v.release)):
vnum += part * (1000 ** i) * 10000
return vnum
class VersionView(APIView):
authentication_classes = (
SessionAuthentication, OAuth2Authentication, DeviceTokenAuthentication, TeamTokenAuthentication
)
def get(self, request, format=None):
return Response({
'pretix': __version__,
'pretix_numeric': numeric_version(__version__),
})

View File

@@ -1,5 +1,4 @@
from django.apps import AppConfig
from django.conf import settings
class PretixBaseConfig(AppConfig):
@@ -13,7 +12,8 @@ class PretixBaseConfig(AppConfig):
from . import invoice # NOQA
from . import notifications # NOQA
from . import email # NOQA
from .services import auth, checkin, export, mail, tickets, cart, orders, invoices, cleanup, update_check, quotas, notifications, vouchers # NOQA
from .services import auth, checkin, export, mail, tickets, cart, orderimport, orders, invoices, cleanup, update_check, quotas, notifications, vouchers # NOQA
from django.conf import settings
try:
from .celery_app import app as celery_app # NOQA

View File

@@ -9,7 +9,7 @@ from django.core.mail.backends.smtp import EmailBackend
from django.dispatch import receiver
from django.template.loader import get_template
from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import get_language, ugettext_lazy as _
from inlinestyler.utils import inline_css
from pretix.base.i18n import LazyCurrencyNumber, LazyDate, LazyNumber
@@ -112,7 +112,8 @@ class TemplateBasedMailRenderer(BaseHTMLMailRenderer):
'site_url': settings.SITE_URL,
'body': body_md,
'subject': str(subject),
'color': '#8E44B3'
'color': '#8E44B3',
'rtl': get_language() in settings.LANGUAGES_RTL
}
if self.event:
htmlctx['event'] = self.event
@@ -135,15 +136,22 @@ class TemplateBasedMailRenderer(BaseHTMLMailRenderer):
class ClassicMailRenderer(TemplateBasedMailRenderer):
verbose_name = _('pretix default')
verbose_name = _('Default')
identifier = 'classic'
thumbnail_filename = 'pretixbase/email/thumb.png'
template_name = 'pretixbase/email/plainwrapper.html'
class UnembellishedMailRenderer(TemplateBasedMailRenderer):
verbose_name = _('Simple with logo')
identifier = 'simple_logo'
thumbnail_filename = 'pretixbase/email/thumb_simple_logo.png'
template_name = 'pretixbase/email/simple_logo.html'
@receiver(register_html_mail_renderers, dispatch_uid="pretixbase_email_renderers")
def base_renderers(sender, **kwargs):
return [ClassicMailRenderer]
return [ClassicMailRenderer, UnembellishedMailRenderer]
class BaseMailTextPlaceholder:

View File

@@ -1,10 +1,12 @@
import io
import tempfile
from collections import OrderedDict
from decimal import Decimal
from typing import Tuple
from defusedcsv import csv
from django import forms
from django.utils.formats import localize
from django.utils.translation import ugettext, ugettext_lazy as _
from openpyxl import Workbook
from openpyxl.cell.cell import KNOWN_TYPES
@@ -117,18 +119,26 @@ class ListExporter(BaseExporter):
if output_file:
writer = csv.writer(output_file, **kwargs)
for line in self.iterate_list(form_data):
line = [
localize(f) if isinstance(f, Decimal) else f
for f in line
]
writer.writerow(line)
return self.get_filename() + '.csv', 'text/csv', None
else:
output = io.StringIO()
writer = csv.writer(output, **kwargs)
for line in self.iterate_list(form_data):
line = [
localize(f) if isinstance(f, Decimal) else f
for f in line
]
writer.writerow(line)
return self.get_filename() + '.csv', 'text/csv', output.getvalue().encode("utf-8")
def _render_xlsx(self, form_data, output_file=None):
wb = Workbook()
ws = wb.get_active_sheet()
ws = wb.active
try:
ws.title = str(self.verbose_name)
except:
@@ -196,18 +206,26 @@ class MultiSheetListExporter(ListExporter):
if output_file:
writer = csv.writer(output_file, **kwargs)
for line in self.iterate_sheet(form_data, sheet):
line = [
localize(f) if isinstance(f, Decimal) else f
for f in line
]
writer.writerow(line)
return self.get_filename() + '.csv', 'text/csv', None
else:
output = io.StringIO()
writer = csv.writer(output, **kwargs)
for line in self.iterate_sheet(form_data, sheet):
line = [
localize(f) if isinstance(f, Decimal) else f
for f in line
]
writer.writerow(line)
return self.get_filename() + '.csv', 'text/csv', output.getvalue().encode("utf-8")
def _render_xlsx(self, form_data, output_file=None):
wb = Workbook()
ws = wb.get_active_sheet()
ws = wb.active
wb.remove(ws)
for s, l in self.sheets:
ws = wb.create_sheet(str(l))

View File

@@ -3,9 +3,11 @@ from decimal import Decimal
import pytz
from django import forms
from django.db.models import DateTimeField, F, Max, OuterRef, Subquery, Sum
from django.db.models import (
Count, DateTimeField, F, IntegerField, Max, OuterRef, Subquery, Sum,
)
from django.dispatch import receiver
from django.utils.formats import date_format, localize
from django.utils.formats import date_format
from django.utils.translation import pgettext, ugettext as _, ugettext_lazy
from pretix.base.models import (
@@ -80,8 +82,12 @@ class OrderListExporter(MultiSheetListExporter):
'm'
).order_by()
s = OrderPosition.objects.filter(
order=OuterRef('pk')
).order_by().values('order').annotate(k=Count('id')).values('k')
qs = self.event.orders.annotate(
payment_date=Subquery(p_date, output_field=DateTimeField())
payment_date=Subquery(p_date, output_field=DateTimeField()),
pcnt=Subquery(s, output_field=IntegerField())
).select_related('invoice_address').prefetch_related('invoices')
if form_data['paid_only']:
qs = qs.filter(status=Order.STATUS_PAID)
@@ -111,6 +117,7 @@ class OrderListExporter(MultiSheetListExporter):
headers.append(_('Sales channel'))
headers.append(_('Requires special attention'))
headers.append(_('Comment'))
headers.append(_('Positions'))
yield headers
@@ -134,7 +141,7 @@ class OrderListExporter(MultiSheetListExporter):
for order in qs.order_by('datetime'):
row = [
order.code,
localize(order.total),
order.total,
order.get_status_display(),
order.email,
order.datetime.astimezone(tz).strftime('%Y-%m-%d'),
@@ -163,7 +170,7 @@ class OrderListExporter(MultiSheetListExporter):
row += [
order.payment_date.astimezone(tz).strftime('%Y-%m-%d') if order.payment_date else '',
localize(full_fee_sum_cache.get(order.id) or Decimal('0.00')),
full_fee_sum_cache.get(order.id) or Decimal('0.00'),
order.locale,
]
@@ -173,16 +180,19 @@ class OrderListExporter(MultiSheetListExporter):
{'grosssum': Decimal('0.00'), 'taxsum': Decimal('0.00')})
row += [
localize(taxrate_values['grosssum'] + fee_taxrate_values['grosssum']),
localize(taxrate_values['grosssum'] - taxrate_values['taxsum']
+ fee_taxrate_values['grosssum'] - fee_taxrate_values['taxsum']),
localize(taxrate_values['taxsum'] + fee_taxrate_values['taxsum']),
taxrate_values['grosssum'] + fee_taxrate_values['grosssum'],
(
taxrate_values['grosssum'] - taxrate_values['taxsum'] +
fee_taxrate_values['grosssum'] - fee_taxrate_values['taxsum']
),
taxrate_values['taxsum'] + fee_taxrate_values['taxsum'],
]
row.append(', '.join([i.number for i in order.invoices.all()]))
row.append(order.sales_channel)
row.append(_('Yes') if order.checkin_attention else _('No'))
row.append(order.comment or "")
row.append(order.pcnt)
yield row
def iterate_fees(self, form_data: dict):
@@ -264,7 +274,7 @@ class OrderListExporter(MultiSheetListExporter):
'order', 'order__invoice_address', 'item', 'variation',
'voucher', 'tax_rule'
).prefetch_related(
'answers', 'answers__question'
'answers', 'answers__question', 'answers__options'
)
if form_data['paid_only']:
qs = qs.filter(order__status=Order.STATUS_PAID)
@@ -299,8 +309,15 @@ class OrderListExporter(MultiSheetListExporter):
_('Pseudonymization ID'),
]
questions = list(self.event.questions.all())
options = {}
for q in questions:
headers.append(str(q.question))
if q.type == Question.TYPE_CHOICE_MULTIPLE:
options[q.pk] = []
for o in q.options.all():
headers.append(str(q.question) + ' ' + str(o.answer))
options[q.pk].append(o)
else:
headers.append(str(q.question))
headers += [
_('Company'),
_('Invoice address name'),
@@ -354,12 +371,19 @@ class OrderListExporter(MultiSheetListExporter):
for a in op.answers.all():
# We do not want to localize Date, Time and Datetime question answers, as those can lead
# to difficulties parsing the data (for example 2019-02-01 may become Février, 2019 01 in French).
if a.question.type in Question.UNLOCALIZED_TYPES:
if a.question.type == Question.TYPE_CHOICE_MULTIPLE:
acache[a.question_id] = set(o.pk for o in a.options.all())
elif a.question.type in Question.UNLOCALIZED_TYPES:
acache[a.question_id] = a.answer
else:
acache[a.question_id] = str(a)
for q in questions:
row.append(acache.get(q.pk, ''))
if q.type == Question.TYPE_CHOICE_MULTIPLE:
for o in options[q.pk]:
row.append(_('Yes') if o.pk in acache.get(q.pk, set()) else _('No'))
else:
row.append(acache.get(q.pk, ''))
try:
row += [
order.invoice_address.company,
@@ -450,7 +474,7 @@ class PaymentListExporter(ListExporter):
d2,
obj.get_state_display(),
obj.state,
localize(obj.amount * (-1 if isinstance(obj, OrderRefund) else 1)),
obj.amount * (-1 if isinstance(obj, OrderRefund) else 1),
provider_names.get(obj.provider, obj.provider)
]
yield row
@@ -531,10 +555,11 @@ class InvoiceDataExporter(MultiSheetListExporter):
_('Foreign currency rate'),
_('Total value (with taxes)'),
_('Total value (without taxes)'),
_('Payment matching IDs'),
]
qs = self.event.invoices.order_by('full_invoice_no').select_related(
'order', 'refers'
).annotate(
).prefetch_related('order__payments').annotate(
total_gross=Subquery(
InvoiceLine.objects.filter(
invoice=OuterRef('pk')
@@ -551,6 +576,16 @@ class InvoiceDataExporter(MultiSheetListExporter):
)
)
for i in qs:
pmis = []
for p in i.order.payments.all():
if p.state in (OrderPayment.PAYMENT_STATE_CONFIRMED, OrderPayment.PAYMENT_STATE_CREATED,
OrderPayment.PAYMENT_STATE_PENDING, OrderPayment.PAYMENT_STATE_REFUNDED):
pprov = p.payment_provider
if pprov:
mid = pprov.matching_id(p)
if mid:
pmis.append(mid)
pmi = '\n'.join(pmis)
yield [
i.full_invoice_no,
date_format(i.date, "SHORT_DATE_FORMAT"),
@@ -581,6 +616,7 @@ class InvoiceDataExporter(MultiSheetListExporter):
i.foreign_currency_rate,
i.total_gross if i.total_gross else Decimal('0.00'),
Decimal(i.total_net if i.total_net else '0.00').quantize(Decimal('0.01')),
pmi
]
elif sheet == 'lines':
yield [

View File

@@ -8,7 +8,6 @@ from django.utils.crypto import get_random_string
from formtools.wizard.views import SessionWizardView
from hierarkey.forms import HierarkeyForm
from pretix.base.models import Event
from pretix.base.reldate import RelativeDateField, RelativeDateTimeField
from .validators import PlaceholderValidator # NOQA
@@ -51,19 +50,33 @@ class I18nInlineFormSet(i18nfield.forms.I18nInlineFormSet):
class SettingsForm(i18nfield.forms.I18nFormMixin, HierarkeyForm):
auto_fields = []
def __init__(self, *args, **kwargs):
from pretix.base.settings import DEFAULTS
self.obj = kwargs.get('obj', None)
self.locales = self.obj.settings.get('locales') if self.obj else kwargs.pop('locales', None)
kwargs['attribute_name'] = 'settings'
kwargs['locales'] = self.locales
kwargs['initial'] = self.obj.settings.freeze()
super().__init__(*args, **kwargs)
for fname in self.auto_fields:
kwargs = DEFAULTS[fname].get('form_kwargs', {})
kwargs.setdefault('required', False)
field = DEFAULTS[fname]['form_class'](
**kwargs
)
if isinstance(field, i18nfield.forms.I18nFormField):
field.widget.enabled_locales = self.locales
self.fields[fname] = field
for k, f in self.fields.items():
if isinstance(f, (RelativeDateTimeField, RelativeDateField)):
f.set_event(self.obj)
def get_new_filename(self, name: str) -> str:
from pretix.base.models import Event
nonce = get_random_string(length=8)
if isinstance(self.obj, Event):
fname = '%s/%s/%s.%s.%s' % (

View File

@@ -32,7 +32,8 @@ class LoginForm(forms.Form):
for k, f in backend.login_form_fields.items():
self.fields[k] = f
if not settings.PRETIX_LONG_SESSIONS:
# Authentication backends which use urls cannot have long sessions.
if not settings.PRETIX_LONG_SESSIONS or backend.url:
del self.fields['keep_logged_in']
else:
self.fields.move_to_end('keep_logged_in')
@@ -197,6 +198,7 @@ class ReauthForm(forms.Form):
self.request = request
self.user = user
self.backend = backend
self.backend.url = backend.authentication_url(self.request)
super().__init__(*args, **kwargs)
for k, f in backend.login_form_fields.items():
self.fields[k] = f

View File

@@ -6,9 +6,6 @@ from django.utils.functional import lazy
from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _
from pretix.base.models import OrderPosition
from pretix.multidomain.urlreverse import eventreverse
class DatePickerWidget(forms.DateInput):
def __init__(self, attrs=None, date_format=None):
@@ -71,6 +68,9 @@ class UploadedFileWidget(forms.ClearableFileInput):
@property
def url(self):
from pretix.base.models import OrderPosition
from pretix.multidomain.urlreverse import eventreverse
if isinstance(self.position, OrderPosition):
return eventreverse(self.event, 'presale:event.order.download.answer', kwargs={
'order': self.position.order.code,

View File

@@ -28,7 +28,7 @@ from reportlab.platypus import (
)
from pretix.base.decimal import round_decimal
from pretix.base.models import Event, Invoice
from pretix.base.models import Event, Invoice, Order
from pretix.base.signals import register_invoice_renderers
from pretix.base.templatetags.money import money_filter
@@ -490,10 +490,13 @@ class ClassicInvoiceRenderer(BaseReportlabInvoiceRenderer):
story = [
NextPageTemplate('FirstPage'),
Paragraph(pgettext('invoice', 'Invoice')
if not self.invoice.is_cancellation
else pgettext('invoice', 'Cancellation'),
self.stylesheet['Heading1']),
Paragraph(
(
pgettext('invoice', 'Tax Invoice') if str(self.invoice.invoice_from_country) == 'AU'
else pgettext('invoice', 'Invoice')
) if not self.invoice.is_cancellation else pgettext('invoice', 'Cancellation'),
self.stylesheet['Heading1']
),
Spacer(1, 5 * mm),
NextPageTemplate('OtherPages'),
]
@@ -556,6 +559,20 @@ class ClassicInvoiceRenderer(BaseReportlabInvoiceRenderer):
])
colwidths = [a * doc.width for a in (.65, .05, .30)]
if self.invoice.event.settings.invoice_show_payments and not self.invoice.is_cancellation and \
self.invoice.order.status == Order.STATUS_PENDING:
pending_sum = self.invoice.order.pending_sum
if pending_sum != total:
tdata.append([pgettext('invoice', 'Received payments')] + (['', '', ''] if has_taxes else ['']) + [
money_filter(pending_sum - total, self.invoice.event.currency)
])
tdata.append([pgettext('invoice', 'Outstanding payments')] + (['', '', ''] if has_taxes else ['']) + [
money_filter(pending_sum, self.invoice.event.currency)
])
tstyledata += [
('FONTNAME', (0, len(tdata) - 3), (-1, len(tdata) - 3), self.font_bold),
]
table = Table(tdata, colWidths=colwidths, repeatRows=1)
table.setStyle(TableStyle(tstyledata))
story.append(table)

View File

@@ -0,0 +1,30 @@
# Generated by Django 2.2.7 on 2019-12-15 15:22
from decimal import Decimal
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0141_seat_sorting_rank'),
]
operations = [
migrations.AddField(
model_name='cartposition',
name='price_before_voucher',
field=models.DecimalField(decimal_places=2, max_digits=10, null=True),
),
migrations.AddField(
model_name='orderposition',
name='price_before_voucher',
field=models.DecimalField(decimal_places=2, max_digits=10, null=True),
),
migrations.AddField(
model_name='voucher',
name='budget',
field=models.DecimalField(decimal_places=2, max_digits=10, null=True),
),
]

View File

@@ -0,0 +1,28 @@
# Generated by Django 2.2.4 on 2020-02-17 12:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0142_auto_20191215_1522'),
]
operations = [
migrations.AddField(
model_name='seat',
name='row_label',
field=models.CharField(max_length=190, null=True),
),
migrations.AddField(
model_name='seat',
name='seat_label',
field=models.CharField(max_length=190, null=True),
),
migrations.AlterField(
model_name='giftcard',
name='secret',
field=models.CharField(db_index=True, max_length=190),
),
]

View File

@@ -293,7 +293,7 @@ class Event(EventMixin, LoggedModel):
"This will be used in URLs, order codes, invoice numbers, and bank transfer references."),
validators=[
RegexValidator(
regex="^[a-zA-Z0-9.-]+$",
regex="^[a-zA-Z0-9][a-zA-Z0-9.-]+$",
message=_("The slug may only contain letters, numbers, dots and dashes."),
),
EventSlugBanlistValidator()
@@ -363,6 +363,14 @@ class Event(EventMixin, LoggedModel):
def __str__(self):
return str(self.name)
def set_defaults(self):
"""
This will be called after event creation, but only if the event was not created by copying an existing one.
This way, we can use this to introduce new default settings to pretix that do not affect existing events.
"""
self.settings.invoice_renderer = 'modern1'
self.settings.invoice_include_expire_date = True
@property
def social_image(self):
from pretix.multidomain.urlreverse import build_absolute_uri
@@ -377,7 +385,7 @@ class Event(EventMixin, LoggedModel):
if img:
return urljoin(build_absolute_uri(self, 'presale:event.index'), img)
def free_seats(self, ignore_voucher=None):
def free_seats(self, ignore_voucher=None, sales_channel='web'):
from .orders import CartPosition, Order, OrderPosition
from .vouchers import Voucher
vqs = Voucher.objects.filter(
@@ -389,7 +397,7 @@ class Event(EventMixin, LoggedModel):
)
if ignore_voucher:
vqs = vqs.exclude(pk=ignore_voucher.pk)
return self.seats.annotate(
qs = self.seats.annotate(
has_order=Exists(
OrderPosition.objects.filter(
order__event=self,
@@ -407,7 +415,10 @@ class Event(EventMixin, LoggedModel):
has_voucher=Exists(
vqs
)
).filter(has_order=False, has_cart=False, has_voucher=False, blocked=False)
).filter(has_order=False, has_cart=False, has_voucher=False)
if sales_channel not in self.settings.seating_allow_blocked_seats_for_channel:
qs = qs.filter(blocked=False)
return qs
@property
def presale_has_ended(self):
@@ -511,6 +522,7 @@ class Event(EventMixin, LoggedModel):
self.is_public = other.is_public
self.testmode = other.testmode
self.save()
self.log_action('pretix.object.cloned', data={'source': other.slug, 'source_id': other.pk})
tax_map = {}
for t in other.tax_rules.all():
@@ -518,6 +530,7 @@ class Event(EventMixin, LoggedModel):
t.pk = None
t.event = self
t.save()
t.log_action('pretix.object.cloned')
category_map = {}
for c in ItemCategory.objects.filter(event=other):
@@ -525,6 +538,7 @@ class Event(EventMixin, LoggedModel):
c.pk = None
c.event = self
c.save()
c.log_action('pretix.object.cloned')
item_map = {}
variation_map = {}
@@ -540,6 +554,7 @@ class Event(EventMixin, LoggedModel):
if i.tax_rule_id:
i.tax_rule = tax_map[i.tax_rule_id]
i.save()
i.log_action('pretix.object.cloned')
for v in vars:
variation_map[v.pk] = v
v.pk = None
@@ -564,6 +579,7 @@ class Event(EventMixin, LoggedModel):
q.cached_availability_time = None
q.closed = False
q.save()
q.log_action('pretix.object.cloned')
for i in items:
if i.pk in item_map:
q.items.add(item_map[i.pk])
@@ -579,6 +595,7 @@ class Event(EventMixin, LoggedModel):
q.pk = None
q.event = self
q.save()
q.log_action('pretix.object.cloned')
for i in items:
q.items.add(item_map[i.pk])
@@ -596,6 +613,7 @@ class Event(EventMixin, LoggedModel):
cl.pk = None
cl.event = self
cl.save()
cl.log_action('pretix.object.cloned')
for i in items:
cl.limit_products.add(item_map[i.pk])
@@ -615,6 +633,8 @@ class Event(EventMixin, LoggedModel):
for s in other.seats.filter(subevent__isnull=True):
s.pk = None
s.event = self
if s.product_id:
s.product = item_map[s.product_id]
s.save()
for s in other.settings._objects.all():
@@ -998,7 +1018,7 @@ class SubEvent(EventMixin, LoggedModel):
def __str__(self):
return '{} - {}'.format(self.name, self.get_date_range_display())
def free_seats(self, ignore_voucher=None):
def free_seats(self, ignore_voucher=None, sales_channel='web'):
from .orders import CartPosition, Order, OrderPosition
from .vouchers import Voucher
vqs = Voucher.objects.filter(
@@ -1011,7 +1031,7 @@ class SubEvent(EventMixin, LoggedModel):
)
if ignore_voucher:
vqs = vqs.exclude(pk=ignore_voucher.pk)
return self.seats.annotate(
qs = self.seats.annotate(
has_order=Exists(
OrderPosition.objects.filter(
order__event_id=self.event_id,
@@ -1031,7 +1051,10 @@ class SubEvent(EventMixin, LoggedModel):
has_voucher=Exists(
vqs
)
).filter(has_order=False, has_cart=False, blocked=False, has_voucher=False)
).filter(has_order=False, has_cart=False, has_voucher=False)
if sales_channel not in self.settings.seating_allow_blocked_seats_for_channel:
qs = qs.filter(blocked=False)
return qs
@cached_property
def settings(self):

View File

@@ -1,6 +1,7 @@
from decimal import Decimal
from django.conf import settings
from django.core.validators import RegexValidator
from django.db import models
from django.db.models import Sum
from django.utils.crypto import get_random_string
@@ -10,10 +11,10 @@ from pretix.base.banlist import banned
from pretix.base.models import LoggedModel
def gen_giftcard_secret():
def gen_giftcard_secret(length=8):
charset = list('ABCDEFGHJKLMNPQRSTUVWXYZ3789')
while True:
code = get_random_string(length=settings.ENTROPY['giftcard_secret'], allowed_chars=charset)
code = get_random_string(length=length, allowed_chars=charset)
if not banned(code) and not GiftCard.objects.filter(secret=code).exists():
return code
@@ -48,9 +49,14 @@ class GiftCard(LoggedModel):
)
secret = models.CharField(
max_length=190,
default=gen_giftcard_secret,
db_index=True,
verbose_name=_('Gift card code'),
validators=[
RegexValidator(
regex="^[a-zA-Z0-9][a-zA-Z0-9.-]+$",
message=_("The giftcard code may only contain letters, numbers, dots and dashes."),
)
],
)
testmode = models.BooleanField(
verbose_name=_('Test mode card'),
@@ -69,6 +75,12 @@ class GiftCard(LoggedModel):
def accepted_by(self, organizer):
return self.issuer == organizer or GiftCardAcceptance.objects.filter(issuer=self.issuer, collector=organizer).exists()
def save(self, *args, **kwargs):
if not self.secret:
self.secret = gen_giftcard_secret(self.issuer.settings.giftcard_length)
super().save(*args, **kwargs)
class Meta:
unique_together = (('secret', 'issuer'),)

View File

@@ -191,6 +191,9 @@ class Invoice(models.Model):
self.prefix = self.event.settings.invoice_numbers_prefix or (self.event.slug.upper() + '-')
if self.is_cancellation:
self.prefix = self.event.settings.invoice_numbers_prefix_cancellations or self.prefix
if '%' in self.prefix:
self.prefix = self.date.strftime(self.prefix)
if not self.invoice_no:
if self.order.testmode:
self.prefix += 'TEST-'

View File

@@ -1106,17 +1106,25 @@ class Question(LoggedModel):
if self.type == Question.TYPE_CHOICE:
try:
return self.options.get(pk=answer)
return self.options.get(Q(pk=answer) | Q(identifier=answer))
except:
raise ValidationError(_('Invalid option selected.'))
elif self.type == Question.TYPE_CHOICE_MULTIPLE:
try:
if isinstance(answer, str):
return list(self.options.filter(pk__in=answer.split(",")))
else:
return list(self.options.filter(pk__in=answer))
except:
if isinstance(answer, str):
l_ = list(self.options.filter(
Q(pk__in=[a for a in answer.split(",") if a.isdigit()]) |
Q(identifier__in=answer.split(","))
))
llen = len(answer.split(','))
else:
l_ = list(self.options.filter(
Q(pk__in=[a for a in answer if isinstance(a, int) or a.isdigit()]) |
Q(identifier__in=answer)
))
llen = len(answer)
if len(l_) != llen:
raise ValidationError(_('Invalid option selected.'))
return l_
elif self.type == Question.TYPE_BOOLEAN:
return answer in ('true', 'True', True)
elif self.type == Question.TYPE_NUMBER:

View File

@@ -400,10 +400,13 @@ class Order(LockModel, LoggedModel):
term_last = self.event.settings.get('payment_term_last', as_type=RelativeDateWrapper)
if term_last:
if self.event.has_subevents and subevents:
term_last = min([
terms = [
term_last.datetime(se).date()
for se in subevents
])
]
if not terms:
return
term_last = min(terms)
else:
term_last = term_last.datetime(self.event).date()
term_last = make_aware(datetime.combine(
@@ -434,10 +437,11 @@ class Order(LockModel, LoggedModel):
until = self.event.settings.get('cancel_allow_user_until', as_type=RelativeDateWrapper)
if until:
if self.event.has_subevents:
return min([
terms = [
until.datetime(se)
for se in self.event.subevents.filter(id__in=self.positions.values_list('subevent', flat=True))
])
]
return min(terms) if terms else None
else:
return until.datetime(self.event)
@@ -586,10 +590,11 @@ class Order(LockModel, LoggedModel):
modify_deadline = self.event.settings.get('last_order_modification_date', as_type=RelativeDateWrapper)
if self.event.has_subevents and modify_deadline:
modify_deadline = min([
dates = [
modify_deadline.datetime(se)
for se in self.event.subevents.filter(id__in=self.positions.values_list('subevent', flat=True))
])
]
modify_deadline = min(dates) if dates else None
elif modify_deadline:
modify_deadline = modify_deadline.datetime(self.event)
@@ -620,10 +625,11 @@ class Order(LockModel, LoggedModel):
dl_date = self.event.settings.get('ticket_download_date', as_type=RelativeDateWrapper)
if dl_date:
if self.event.has_subevents:
dl_date = min([
dates = [
dl_date.datetime(se)
for se in self.event.subevents.filter(id__in=self.positions.values_list('subevent', flat=True))
])
]
dl_date = min(dates) if dates else None
else:
dl_date = dl_date.datetime(self.event)
return dl_date
@@ -648,10 +654,14 @@ class Order(LockModel, LoggedModel):
term_last = self.event.settings.get('payment_term_last', as_type=RelativeDateWrapper)
if term_last:
if self.event.has_subevents:
term_last = min([
terms = [
term_last.datetime(se).date()
for se in self.event.subevents.filter(id__in=self.positions.values_list('subevent', flat=True))
])
]
if terms:
term_last = min(terms)
else:
term_last = None
else:
term_last = term_last.datetime(self.event).date()
term_last = make_aware(datetime.combine(
@@ -687,10 +697,12 @@ class Order(LockModel, LoggedModel):
error_messages = {
'unavailable': _('The ordered product "{item}" is no longer available.'),
'seat_unavailable': _('The seat "{seat}" is no longer available.'),
'voucher_budget': _('The voucher "{voucher}" no longer has sufficient budget.'),
}
now_dt = now_dt or now()
positions = self.positions.all().select_related('item', 'variation', 'seat')
positions = self.positions.all().select_related('item', 'variation', 'seat', 'voucher')
quota_cache = {}
v_budget = {}
try:
for i, op in enumerate(positions):
if op.seat:
@@ -699,6 +711,16 @@ class Order(LockModel, LoggedModel):
if force:
continue
if op.voucher and op.voucher.budget is not None and op.price_before_voucher is not None:
if op.voucher not in v_budget:
v_budget[op.voucher] = op.voucher.budget - op.voucher.budget_used()
disc = op.price_before_voucher - op.price
if disc > v_budget[op.voucher]:
raise Quota.QuotaExceededException(error_messages['voucher_budget'].format(
voucher=op.voucher.code
))
v_budget[op.voucher] -= disc
quotas = list(op.quotas)
if len(quotas) == 0:
raise Quota.QuotaExceededException(error_messages['unavailable'].format(
@@ -888,7 +910,7 @@ class QuestionAnswer(models.Model):
@property
def is_image(self):
return any(self.file.name.endswith(e) for e in ('.jpg', '.png', '.gif', '.tiff', '.bmp', '.jpeg'))
return any(self.file.name.lower().endswith(e) for e in ('.jpg', '.png', '.gif', '.tiff', '.bmp', '.jpeg'))
@property
def file_name(self):
@@ -991,6 +1013,9 @@ class AbstractPosition(models.Model):
verbose_name=_("Variation"),
on_delete=models.PROTECT
)
price_before_voucher = models.DecimalField(
decimal_places=2, max_digits=10, null=True,
)
price = models.DecimalField(
decimal_places=2, max_digits=10,
verbose_name=_("Price")
@@ -1243,6 +1268,36 @@ class OrderPayment(models.Model):
self.order.log_action('pretix.event.order.overpaid', {}, user=user, auth=auth)
order_paid.send(self.order.event, order=self.order)
def fail(self, info=None, user=None, auth=None):
"""
Marks the order as failed and sets info to ``info``, but only if the order is in ``created`` or ``pending``
state. This is equivalent to setting ``state`` to ``OrderPayment.PAYMENT_STATE_FAILED`` and logging a failure,
but it adds strong database logging since we do not want to report a failure for an order that has just
been marked as paid.
"""
with transaction.atomic():
locked_instance = OrderPayment.objects.select_for_update().get(pk=self.pk)
if locked_instance.state not in (OrderPayment.PAYMENT_STATE_CREATED, OrderPayment.PAYMENT_STATE_PENDING):
# Race condition detected, this payment is already confirmed
logger.info('Failed payment {} but ignored due to likely race condition.'.format(
self.full_id,
))
return
if isinstance(info, str):
locked_instance.info = info
elif info:
locked_instance.info_data = info
locked_instance.state = OrderPayment.PAYMENT_STATE_FAILED
locked_instance.save(update_fields=['state', 'info'])
self.refresh_from_db()
self.order.log_action('pretix.event.order.payment.failed', {
'local_id': self.local_id,
'provider': self.provider,
'info': info,
}, user=user, auth=auth)
def confirm(self, count_waitinglist=True, send_mail=True, force=False, user=None, auth=None, mail_text='',
ignore_date=False, lock=True, payment_date=None):
"""
@@ -1270,6 +1325,9 @@ class OrderPayment(models.Model):
locked_instance = OrderPayment.objects.select_for_update().get(pk=self.pk)
if locked_instance.state == self.PAYMENT_STATE_CONFIRMED:
# Race condition detected, this payment is already confirmed
logger.info('Confirmed payment {} but ignored due to likely race condition.'.format(
self.full_id,
))
return
locked_instance.state = self.PAYMENT_STATE_CONFIRMED
@@ -1290,6 +1348,7 @@ class OrderPayment(models.Model):
}, user=user, auth=auth)
if self.order.status in (Order.STATUS_PAID, Order.STATUS_CANCELED):
logger.info('Confirmed payment {} but order is in status {}.'.format(self.full_id, self.order.status))
return
payment_sum = self.order.payments.filter(
@@ -1300,6 +1359,9 @@ class OrderPayment(models.Model):
OrderRefund.REFUND_STATE_CREATED)
).aggregate(s=Sum('amount'))['s'] or Decimal('0.00')
if payment_sum - refund_sum < self.order.total:
logger.info('Confirmed payment {} but payment sum is {} and refund sum is.'.format(
self.full_id, payment_sum, refund_sum
))
return
if (self.order.status == Order.STATUS_PENDING and self.order.expires > now() + timedelta(hours=12)) or not lock:
@@ -1858,8 +1920,9 @@ class OrderPosition(AbstractPosition):
if self.tax_rate is None:
self._calculate_tax()
self.order.touch()
if self.pk is None:
while OrderPosition.all.filter(secret=self.secret).exists():
if not self.pk:
while OrderPosition.all.filter(secret=self.secret,
order__event__organizer_id=self.order.event.organizer_id).exists():
self.secret = generate_position_secret()
if not self.pseudonymization_id:
@@ -1876,9 +1939,10 @@ class OrderPosition(AbstractPosition):
charset = list('ABCDEFGHJKLMNPQRSTUVWXYZ3789')
while True:
code = get_random_string(length=10, allowed_chars=charset)
if not OrderPosition.all.filter(pseudonymization_id=code).exists():
self.pseudonymization_id = code
return
with scopes_disabled():
if not OrderPosition.all.filter(pseudonymization_id=code).exists():
self.pseudonymization_id = code
return
@property
def event(self):
@@ -2033,7 +2097,7 @@ class InvoiceAddress(models.Model):
internal_reference = models.TextField(
verbose_name=_('Internal reference'),
help_text=_('This reference will be printed on your invoice for your convenience.'),
blank=True
blank=True,
)
beneficiary = models.TextField(
verbose_name=_('Beneficiary'),
@@ -2053,6 +2117,13 @@ class InvoiceAddress(models.Model):
self.name_parts = {}
super().save(**kwargs)
@property
def is_empty(self):
return (
not self.name_cached and not self.company and not self.street and not self.zipcode and not self.city
and not self.internal_reference and not self.beneficiary
)
@property
def state_name(self):
sd = pycountry.subdivisions.get(code='{}-{}'.format(self.country, self.state))

View File

@@ -37,7 +37,7 @@ class Organizer(LoggedModel):
"once. This is being used in URLs to refer to your organizer accounts and your events."),
validators=[
RegexValidator(
regex="^[a-zA-Z0-9.-]+$",
regex="^[a-zA-Z0-9][a-zA-Z0-9.-]+$",
message=_("The slug may only contain letters, numbers, dots and dashes.")
),
OrganizerSlugBanlistValidator()

View File

@@ -28,7 +28,8 @@ class SeatingPlanLayoutValidator:
try:
jsonschema.validate(val, schema)
except jsonschema.ValidationError as e:
raise ValidationError(_('Your layout file is not a valid seating plan. Error message: {}').format(str(e)))
e = str(e).replace('%', '%%')
raise ValidationError(_('Your layout file is not a valid seating plan. Error message: {}').format(e))
class SeatingPlan(LoggedModel):
@@ -40,7 +41,7 @@ class SeatingPlan(LoggedModel):
layout = models.TextField(validators=[SeatingPlanLayoutValidator()])
Category = namedtuple('Categrory', 'name')
RawSeat = namedtuple('Seat', 'name guid number row category zone sorting_rank')
RawSeat = namedtuple('Seat', 'name guid number row category zone sorting_rank row_label seat_label')
def __str__(self):
return self.name
@@ -69,11 +70,17 @@ class SeatingPlan(LoggedModel):
# optimization, because this way we do not need to update the rank of very seat if we change a plan a little.
for zi, z in enumerate(self.layout_data['zones']):
for ri, r in enumerate(z['rows']):
row_label = None
if r.get('row_label'):
row_label = r['row_label'].replace("%s", r.get('row_number', str(ri)))
try:
row_rank = int(r['row_number'])
except ValueError:
row_rank = ri
for si, s in enumerate(r['seats']):
seat_label = None
if r.get('seat_label'):
seat_label = r['seat_label'].replace("%s", s.get('seat_number', str(si)))
try:
seat_rank = int(s['seat_number'])
except ValueError:
@@ -87,6 +94,8 @@ class SeatingPlan(LoggedModel):
guid=s['seat_guid'],
name='{} {}'.format(r['row_number'], s['seat_number']), # TODO: Zone? Variable scheme?
row=r['row_number'],
row_label=row_label,
seat_label=seat_label,
zone=z['name'],
category=s['category'],
sorting_rank=rank
@@ -114,7 +123,9 @@ class Seat(models.Model):
name = models.CharField(max_length=190)
zone_name = models.CharField(max_length=190, blank=True, default="")
row_name = models.CharField(max_length=190, blank=True, default="")
row_label = models.CharField(max_length=190, null=True)
seat_number = models.CharField(max_length=190, blank=True, default="")
seat_label = models.CharField(max_length=190, null=True)
seat_guid = models.CharField(max_length=190, db_index=True)
product = models.ForeignKey('Item', null=True, blank=True, related_name='seats', on_delete=models.CASCADE)
blocked = models.BooleanField(default=False)
@@ -127,20 +138,30 @@ class Seat(models.Model):
parts = []
if self.zone_name:
parts.append(self.zone_name)
if self.row_name:
if self.row_label:
parts.append(self.row_label)
elif self.row_name:
parts.append(gettext('Row {number}').format(number=self.row_name))
if self.seat_number:
if self.seat_label:
parts.append(self.seat_label)
elif self.seat_number:
parts.append(gettext('Seat {number}').format(number=self.seat_number))
if not parts:
return self.name
return ', '.join(parts)
def is_available(self, ignore_cart=None, ignore_orderpos=None, ignore_voucher_id=None):
def is_available(self, ignore_cart=None, ignore_orderpos=None, ignore_voucher_id=None, sales_channel='web'):
from .orders import Order
if self.blocked:
if self.blocked and sales_channel not in self.event.settings.seating_allow_blocked_seats_for_channel:
return False
opqs = self.orderposition_set.filter(order__status__in=[Order.STATUS_PENDING, Order.STATUS_PAID])
opqs = self.orderposition_set.filter(
order__status__in=[Order.STATUS_PENDING, Order.STATUS_PAID],
canceled=False
)
cpqs = self.cartposition_set.filter(expires__gte=now())
vqs = self.vouchers.filter(
Q(Q(valid_until__isnull=True) | Q(valid_until__gte=now())) &

View File

@@ -4,7 +4,8 @@ from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import MinLengthValidator
from django.db import models
from django.db.models import Q
from django.db.models import F, OuterRef, Q, Subquery, Sum
from django.db.models.functions import Coalesce
from django.utils.crypto import get_random_string
from django.utils.timezone import now
from django.utils.translation import pgettext_lazy, ugettext_lazy as _
@@ -17,7 +18,7 @@ from ..decimal import round_decimal
from .base import LoggedModel
from .event import Event, SubEvent
from .items import Item, ItemVariation, Quota
from .orders import Order
from .orders import Order, OrderPosition
def _generate_random_code(prefix=None):
@@ -114,6 +115,13 @@ class Voucher(LoggedModel):
verbose_name=_("Redeemed"),
default=0
)
budget = models.DecimalField(
verbose_name=_("Maximum discount budget"),
help_text=_("This is the maximum monetary amount that will be discounted using this voucher across all usages. "
"If this is sum reached, the voucher can no longer be used."),
decimal_places=2, max_digits=10,
null=True, blank=True
)
valid_until = models.DateTimeField(
blank=True, null=True, db_index=True,
verbose_name=_("Valid until")
@@ -430,7 +438,7 @@ class Voucher(LoggedModel):
return False
return True
def calculate_price(self, original_price: Decimal) -> Decimal:
def calculate_price(self, original_price: Decimal, max_discount: Decimal=None) -> Decimal:
"""
Returns how the price given in original_price would be modified if this
voucher is applied, i.e. replaced by a different price or reduced by a
@@ -448,7 +456,9 @@ class Voucher(LoggedModel):
p = original_price
places = settings.CURRENCY_PLACES.get(self.event.currency, 2)
if places < 2:
return p.quantize(Decimal('1') / 10 ** places, ROUND_HALF_UP)
p = p.quantize(Decimal('1') / 10 ** places, ROUND_HALF_UP)
if max_discount is not None:
p = max(p, original_price - max_discount)
return p
return original_price
@@ -460,7 +470,7 @@ class Voucher(LoggedModel):
return Order.objects.filter(all_positions__voucher__in=[self]).distinct()
def seating_available(self):
def seating_available(self, subevent):
kwargs = {}
if self.subevent:
kwargs['subevent'] = self.subevent
@@ -469,4 +479,27 @@ class Voucher(LoggedModel):
elif self.item_id:
return self.item.seat_category_mappings.filter(**kwargs).exists()
else:
return False
return bool(subevent.seating_plan) if subevent else self.event.seating_plan
@classmethod
def annotate_budget_used_orders(cls, qs):
opq = OrderPosition.objects.filter(
voucher_id=OuterRef('pk'),
price_before_voucher__isnull=False,
order__status__in=[
Order.STATUS_PAID,
Order.STATUS_PENDING
]
).order_by().values('voucher_id').annotate(s=Sum(F('price_before_voucher') - F('price'))).values('s')
return qs.annotate(budget_used_orders=Coalesce(Subquery(opq, output_field=models.DecimalField(max_digits=10, decimal_places=2)), Decimal('0.00')))
def budget_used(self):
ops = OrderPosition.objects.filter(
voucher=self,
price_before_voucher__isnull=False,
order__status__in=[
Order.STATUS_PAID,
Order.STATUS_PENDING
]
).aggregate(s=Sum(F('price_before_voucher') - F('price')))['s'] or Decimal('0.00')
return ops

View File

@@ -0,0 +1,612 @@
import re
from decimal import Decimal, DecimalException
import pycountry
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import EmailValidator
from django.utils import formats
from django.utils.functional import cached_property
from django.utils.translation import (
gettext as _, gettext_lazy, pgettext, pgettext_lazy,
)
from django_countries import countries
from django_countries.fields import Country
from pretix.base.channels import get_all_sales_channels
from pretix.base.forms.questions import guess_country
from pretix.base.models import (
ItemVariation, OrderPosition, QuestionAnswer, QuestionOption, Seat,
)
from pretix.base.services.pricing import get_price
from pretix.base.settings import (
COUNTRIES_WITH_STATE_IN_ADDRESS, PERSON_NAME_SCHEMES,
)
from pretix.base.signals import order_import_columns
class ImportColumn:
@property
def identifier(self):
"""
Unique, internal name of the column.
"""
raise NotImplementedError
@property
def verbose_name(self):
"""
Human-readable description of the column
"""
raise NotImplementedError
@property
def initial(self):
"""
Initial value for the form component
"""
return None
@property
def default_value(self):
"""
Internal default value for the assignment of this column. Defaults to ``empty``. Return ``None`` to disable this
option.
"""
return 'empty'
@property
def default_label(self):
"""
Human-readable description of the default assignment of this column, defaults to "Keep empty".
"""
return gettext_lazy('Keep empty')
def __init__(self, event):
self.event = event
def static_choices(self):
"""
This will be called when rendering the form component and allows you to return a list of values that can be
selected by the user statically during import.
:return: list of 2-tuples of strings
"""
return []
def resolve(self, settings, record):
"""
This method will be called to get the raw value for this field, usually by either using a static value or
inspecting the CSV file for the assigned header. You usually do not need to implement this on your own,
the default should be fine.
"""
k = settings.get(self.identifier, self.default_value)
if k == self.default_value:
return None
elif k.startswith('csv:'):
return record.get(k[4:], None) or None
elif k.startswith('static:'):
return k[7:]
raise ValidationError(_('Invalid setting for column "{header}".').format(header=self.verbose_name))
def clean(self, value, previous_values):
"""
Allows you to validate the raw input value for your column. Raise ``ValidationError`` if the value is invalid.
You do not need to include the column or row name or value in the error message as it will automatically be
included.
:param value: Contains the raw value of your column as returned by ``resolve``. This can usually be ``None``,
e.g. if the column is empty or does not exist in this row.
:param previous_values: Dictionary containing the validated values of all columns that have already been validated.
"""
return value
def assign(self, value, order, position, invoice_address, **kwargs):
"""
This will be called to perform the actual import. You are supposed to set attributes on the ``order``, ``position``,
or ``invoice_address`` objects based on the input ``value``. This is called *before* the actual database
transaction, so these three objects do not yet have a primary key. If you want to create related objects, you
need to place them into some sort of internal queue and persist them when ``save`` is called.
"""
pass
def save(self, order):
"""
This will be called to perform the actual import. This is called inside the actual database transaction and the
input object ``order`` has already been saved to the database.
"""
pass
class EmailColumn(ImportColumn):
identifier = 'email'
verbose_name = gettext_lazy('E-mail address')
def clean(self, value, previous_values):
if value:
EmailValidator()(value)
return value
def assign(self, value, order, position, invoice_address, **kwargs):
order.email = value
class SubeventColumn(ImportColumn):
identifier = 'subevent'
verbose_name = pgettext_lazy('subevents', 'Date')
default_value = None
@cached_property
def subevents(self):
return list(self.event.subevents.filter(active=True).order_by('date_from'))
def static_choices(self):
return [
(str(p.pk), str(p)) for p in self.subevents
]
def clean(self, value, previous_values):
if not value:
raise ValidationError(pgettext("subevent", "You need to select a date."))
matches = [
p for p in self.subevents
if str(p.pk) == value or any(
(v and v == value) for v in i18n_flat(p.name)) or p.date_from.isoformat() == value
]
if len(matches) == 0:
raise ValidationError(pgettext("subevent", "No matching date was found."))
if len(matches) > 1:
raise ValidationError(pgettext("subevent", "Multiple matching dates were found."))
return matches[0]
def assign(self, value, order, position, invoice_address, **kwargs):
position.subevent = value
def i18n_flat(l):
if isinstance(l.data, dict):
return l.data.values()
return [l.data]
class ItemColumn(ImportColumn):
identifier = 'item'
verbose_name = gettext_lazy('Product')
default_value = None
@cached_property
def items(self):
return list(self.event.items.filter(active=True))
def static_choices(self):
return [
(str(p.pk), str(p)) for p in self.items
]
def clean(self, value, previous_values):
matches = [
p for p in self.items
if str(p.pk) == value or (p.internal_name and p.internal_name == value) or any(
(v and v == value) for v in i18n_flat(p.name))
]
if len(matches) == 0:
raise ValidationError(_("No matching product was found."))
if len(matches) > 1:
raise ValidationError(_("Multiple matching products were found."))
return matches[0]
def assign(self, value, order, position, invoice_address, **kwargs):
position.item = value
class Variation(ImportColumn):
identifier = 'variation'
verbose_name = gettext_lazy('Product variation')
@cached_property
def items(self):
return list(ItemVariation.objects.filter(
active=True, item__active=True, item__event=self.event
).select_related('item'))
def static_choices(self):
return [
(str(p.pk), '{} {}'.format(p.item, p.value)) for p in self.items
]
def clean(self, value, previous_values):
if value:
matches = [
p for p in self.items
if str(p.pk) == value or any((v and v == value) for v in i18n_flat(p.value)) and p.item_id == previous_values['item'].pk
]
if len(matches) == 0:
raise ValidationError(_("No matching variation was found."))
if len(matches) > 1:
raise ValidationError(_("Multiple matching variations were found."))
return matches[0]
elif previous_values['item'].variations.exists():
raise ValidationError(_("You need to select a variation for this product."))
return value
def assign(self, value, order, position, invoice_address, **kwargs):
position.variation = value
class InvoiceAddressCompany(ImportColumn):
identifier = 'invoice_address_company'
@property
def verbose_name(self):
return _('Invoice address') + ': ' + _('Company')
def assign(self, value, order, position, invoice_address, **kwargs):
invoice_address.company = value or ''
invoice_address.is_business = bool(value)
class InvoiceAddressNamePart(ImportColumn):
def __init__(self, event, key, label):
self.key = key
self.label = label
super().__init__(event)
@property
def verbose_name(self):
return _('Invoice address') + ': ' + str(self.label)
@property
def identifier(self):
return 'invoice_address_name_{}'.format(self.key)
def assign(self, value, order, position, invoice_address, **kwargs):
invoice_address.name_parts[self.key] = value or ''
class InvoiceAddressStreet(ImportColumn):
identifier = 'invoice_address_street'
@property
def verbose_name(self):
return _('Invoice address') + ': ' + _('Address')
def assign(self, value, order, position, invoice_address, **kwargs):
invoice_address.address = value or ''
class InvoiceAddressZip(ImportColumn):
identifier = 'invoice_address_zipcode'
@property
def verbose_name(self):
return _('Invoice address') + ': ' + _('ZIP code')
def assign(self, value, order, position, invoice_address, **kwargs):
invoice_address.zipcode = value or ''
class InvoiceAddressCity(ImportColumn):
identifier = 'invoice_address_city'
@property
def verbose_name(self):
return _('Invoice address') + ': ' + _('City')
def assign(self, value, order, position, invoice_address, **kwargs):
invoice_address.city = value or ''
class InvoiceAddressCountry(ImportColumn):
identifier = 'invoice_address_country'
default_value = None
@property
def initial(self):
return 'static:' + str(guess_country(self.event))
@property
def verbose_name(self):
return _('Invoice address') + ': ' + _('Country')
def static_choices(self):
return list(countries)
def clean(self, value, previous_values):
if value and not Country(value).numeric:
raise ValidationError(_("Please enter a valid country code."))
return value
def assign(self, value, order, position, invoice_address, **kwargs):
invoice_address.country = value or ''
class InvoiceAddressState(ImportColumn):
identifier = 'invoice_address_state'
@property
def verbose_name(self):
return _('Invoice address') + ': ' + _('State')
def clean(self, value, previous_values):
if value:
if previous_values.get('invoice_address_country') not in COUNTRIES_WITH_STATE_IN_ADDRESS:
raise ValidationError(_("States are not supported for this country."))
types, form = COUNTRIES_WITH_STATE_IN_ADDRESS[previous_values.get('invoice_address_country')]
match = [
s for s in pycountry.subdivisions.get(country_code=previous_values.get('invoice_address_country'))
if s.type in types and (s.code[3:] == value or s.name == value)
]
if len(match) == 0:
raise ValidationError(_("Please enter a valid state."))
return match[0].code[3:]
def assign(self, value, order, position, invoice_address, **kwargs):
invoice_address.state = value or ''
class InvoiceAddressVATID(ImportColumn):
identifier = 'invoice_address_vat_id'
@property
def verbose_name(self):
return _('Invoice address') + ': ' + _('VAT ID')
def assign(self, value, order, position, invoice_address, **kwargs):
invoice_address.vat_id = value or ''
class InvoiceAddressReference(ImportColumn):
identifier = 'invoice_address_internal_reference'
@property
def verbose_name(self):
return _('Invoice address') + ': ' + _('Internal reference')
def assign(self, value, order, position, invoice_address, **kwargs):
invoice_address.internal_reference = value or ''
class AttendeeNamePart(ImportColumn):
def __init__(self, event, key, label):
self.key = key
self.label = label
super().__init__(event)
@property
def verbose_name(self):
return _('Attendee name') + ': ' + str(self.label)
@property
def identifier(self):
return 'attendee_name_{}'.format(self.key)
def assign(self, value, order, position, invoice_address, **kwargs):
position.attendee_name_parts[self.key] = value or ''
class AttendeeEmail(ImportColumn):
identifier = 'attendee_email'
verbose_name = gettext_lazy('Attendee e-mail address')
def clean(self, value, previous_values):
if value:
EmailValidator()(value)
return value
def assign(self, value, order, position, invoice_address, **kwargs):
position.attendee_email = value
class Price(ImportColumn):
identifier = 'price'
verbose_name = gettext_lazy('Price')
default_label = gettext_lazy('Calculate from product')
def clean(self, value, previous_values):
if value not in (None, ''):
value = formats.sanitize_separators(re.sub(r'[^0-9.,-]', '', value))
try:
value = Decimal(value)
except (DecimalException, TypeError):
raise ValidationError(_('You entered an invalid number.'))
return value
def assign(self, value, order, position, invoice_address, **kwargs):
if value is None:
p = get_price(position.item, position.variation, position.voucher, subevent=position.subevent,
invoice_address=invoice_address)
else:
p = get_price(position.item, position.variation, position.voucher, subevent=position.subevent,
invoice_address=invoice_address, custom_price=value, force_custom_price=True)
position.price = p.gross
position.tax_rule = position.item.tax_rule
position.tax_rate = p.rate
position.tax_value = p.tax
class Secret(ImportColumn):
identifier = 'secret'
verbose_name = gettext_lazy('Ticket code')
default_label = gettext_lazy('Generate automatically')
def __init__(self, *args):
self._cached = set()
super().__init__(*args)
def clean(self, value, previous_values):
if value and (value in self._cached or OrderPosition.all.filter(order__event=self.event, secret=value).exists()):
raise ValidationError(
_('You cannot assign a position secret that already exists.')
)
self._cached.add(value)
return value
def assign(self, value, order, position, invoice_address, **kwargs):
if value:
position.secret = value
class Locale(ImportColumn):
identifier = 'locale'
verbose_name = gettext_lazy('Order locale')
default_value = None
@property
def initial(self):
return 'static:' + self.event.settings.locale
def static_choices(self):
locale_names = dict(settings.LANGUAGES)
return [
(a, locale_names[a]) for a in self.event.settings.locales
]
def clean(self, value, previous_values):
if not value:
value = self.event.settings.locale
if value not in self.event.settings.locales:
raise ValidationError(_("Please enter a valid language code."))
return value
def assign(self, value, order, position, invoice_address, **kwargs):
order.locale = value
class Saleschannel(ImportColumn):
identifier = 'sales_channel'
verbose_name = gettext_lazy('Sales channel')
def static_choices(self):
return [
(sc.identifier, sc.verbose_name) for sc in get_all_sales_channels().values()
]
def clean(self, value, previous_values):
if not value:
value = 'web'
if value not in get_all_sales_channels():
raise ValidationError(_("Please enter a valid sales channel."))
return value
def assign(self, value, order, position, invoice_address, **kwargs):
order.sales_channel = value
class SeatColumn(ImportColumn):
identifier = 'seat'
verbose_name = gettext_lazy('Seat ID')
def __init__(self, *args):
self._cached = set()
super().__init__(*args)
def clean(self, value, previous_values):
if value:
try:
value = Seat.objects.get(
seat_guid=value,
subevent=previous_values.get('subevent')
)
except Seat.DoesNotExist:
raise ValidationError(_('No matching seat was found.'))
if not value.is_available() or value in self._cached:
raise ValidationError(
_('The seat you selected has already been taken. Please select a different seat.'))
self._cached.add(value)
elif previous_values['item'].seat_category_mappings.filter(subevent=previous_values.get('subevent')).exists():
raise ValidationError(_('You need to select a specific seat.'))
return value
def assign(self, value, order, position, invoice_address, **kwargs):
position.seat = value
class Comment(ImportColumn):
identifier = 'comment'
verbose_name = gettext_lazy('Comment')
def assign(self, value, order, position, invoice_address, **kwargs):
order.comment = value or ''
class QuestionColumn(ImportColumn):
def __init__(self, event, q):
self.q = q
super().__init__(event)
@property
def verbose_name(self):
return _('Question') + ': ' + str(self.q.question)
@property
def identifier(self):
return 'question_{}'.format(self.q.pk)
def clean(self, value, previous_values):
if value:
return self.q.clean_answer(value)
def assign(self, value, order, position, invoice_address, **kwargs):
if value:
if not hasattr(order, '_answers'):
order._answers = []
if isinstance(value, QuestionOption):
a = QuestionAnswer(orderposition=position, question=self.q, answer=str(value))
a._options = [value]
order._answers.append(a)
elif isinstance(value, list):
a = QuestionAnswer(orderposition=position, 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), orderposition=position))
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)
def get_all_columns(event):
default = []
if event.has_subevents:
default.append(SubeventColumn(event))
default += [
EmailColumn(event),
ItemColumn(event),
Variation(event),
InvoiceAddressCompany(event),
]
scheme = PERSON_NAME_SCHEMES.get(event.settings.name_scheme)
for n, l, w in scheme['fields']:
default.append(InvoiceAddressNamePart(event, n, l))
default += [
InvoiceAddressStreet(event),
InvoiceAddressZip(event),
InvoiceAddressCity(event),
InvoiceAddressCountry(event),
InvoiceAddressState(event),
InvoiceAddressVATID(event),
InvoiceAddressReference(event),
]
for n, l, w in scheme['fields']:
default.append(AttendeeNamePart(event, n, l))
default += [
AttendeeEmail(event),
Price(event),
Secret(event),
Locale(event),
Saleschannel(event),
SeatColumn(event),
Comment(event)
]
for q in event.questions.exclude(type='F'):
default.append(QuestionColumn(event, q))
for recv, resp in order_import_columns.send(sender=event):
default += resp
return default

View File

@@ -1,3 +1,4 @@
import hashlib
import json
import logging
from collections import OrderedDict
@@ -14,6 +15,7 @@ from django.dispatch import receiver
from django.forms import Form
from django.http import HttpRequest
from django.template.loader import get_template
from django.utils.crypto import get_random_string
from django.utils.timezone import now
from django.utils.translation import pgettext_lazy, ugettext_lazy as _
from django_countries import Countries
@@ -32,7 +34,7 @@ from pretix.base.signals import register_payment_providers
from pretix.base.templatetags.money import money_filter
from pretix.base.templatetags.rich_text import rich_text
from pretix.helpers.money import DecimalTextInput
from pretix.multidomain.urlreverse import eventreverse
from pretix.multidomain.urlreverse import build_absolute_uri, eventreverse
from pretix.presale.views import get_cart, get_cart_total
from pretix.presale.views.cart import cart_session, get_or_create_cart_id
@@ -204,6 +206,13 @@ class BasePaymentProvider:
implementation.
"""
places = settings.CURRENCY_PLACES.get(self.event.currency, 2)
if not self.settings.get('_hidden_seed'):
self.settings.set('_hidden_seed', get_random_string(64))
hidden_url = build_absolute_uri(self.event, 'presale:event.payment.unlock', kwargs={
'hash': hashlib.sha256((self.settings._hidden_seed + self.event.slug).encode()).hexdigest(),
})
d = OrderedDict([
('_enabled',
forms.BooleanField(
@@ -297,7 +306,30 @@ class BasePaymentProvider:
widget=forms.CheckboxSelectMultiple,
help_text=_(
'Only allow the usage of this payment provider in the following sales channels'),
))
)),
('_hidden',
forms.BooleanField(
label=_('Hide payment method'),
required=False,
help_text=_(
'The payment method will not be shown by default but only to people who enter the shop through '
'a special link.'
),
)),
('_hidden_url',
forms.URLField(
label=_('Link to enable payment method'),
widget=forms.TextInput(attrs={
'readonly': 'readonly',
'data-display-dependency': '#id_%s_hidden' % self.settings.get_prefix(),
'value': hidden_url,
}),
required=False,
initial=hidden_url,
help_text=_(
'Share this link with customers who should use this payment method.'
),
)),
])
d['_restricted_countries']._as_type = list
d['_restrict_to_sales_channels']._as_type = list
@@ -378,28 +410,31 @@ class BasePaymentProvider:
availability_date = self.settings.get('_availability_date', as_type=RelativeDateWrapper)
if availability_date:
if self.event.has_subevents and cart_id:
availability_date = min([
dates = [
availability_date.datetime(se).date()
for se in self.event.subevents.filter(
id__in=CartPosition.objects.filter(
cart_id=cart_id, event=self.event
).values_list('subevent', flat=True)
)
])
]
availability_date = min(dates) if dates else None
elif self.event.has_subevents and order:
availability_date = min([
dates = [
availability_date.datetime(se).date()
for se in self.event.subevents.filter(
id__in=order.positions.values_list('subevent', flat=True)
)
])
]
availability_date = min(dates) if dates else None
elif self.event.has_subevents:
logger.error('Payment provider is not subevent-ready.')
return False
else:
availability_date = availability_date.datetime(self.event).date()
return availability_date >= now_dt.astimezone(tz).date()
if availability_date:
return availability_date >= now_dt.astimezone(tz).date()
return True
@@ -433,6 +468,11 @@ class BasePaymentProvider:
if self.settings._total_min is not None:
pricing = pricing and total >= Decimal(self.settings._total_min)
if self.settings.get('_hidden', as_type=bool):
hashes = request.session.get('pretix_unlock_hashes', [])
if hashlib.sha256((self.settings._hidden_seed + self.event.slug).encode()).hexdigest() not in hashes:
return False
def get_invoice_address():
if not hasattr(request, '_checkout_flow_invoice_address'):
cs = cart_session(request)
@@ -602,6 +642,9 @@ class BasePaymentProvider:
if self.settings._total_min is not None and ps < Decimal(self.settings._total_min):
return False
if self.settings.get('_hidden', as_type=bool):
return False
restricted_countries = self.settings.get('_restricted_countries', as_type=list)
if restricted_countries:
try:
@@ -687,7 +730,7 @@ class BasePaymentProvider:
On failure, you should raise a PaymentException.
"""
payment.state = OrderPayment.PAYMENT_STATE_CANCELED
payment.save()
payment.save(update_fields=['state'])
def execute_refund(self, refund: OrderRefund):
"""
@@ -721,6 +764,16 @@ class BasePaymentProvider:
"""
return {}
def matching_id(self, payment: OrderPayment):
"""
Will be called to get an ID for a matching this payment when comparing pretix records with records of an external
source. This should return the main transaction ID for your API.
:param payment: The payment in question.
:return: A string or None
"""
return None
class PaymentException(Exception):
pass

View File

@@ -1,7 +1,7 @@
import copy
import itertools
import logging
import os
import re
import subprocess
import tempfile
import uuid
@@ -9,12 +9,13 @@ from collections import OrderedDict
from functools import partial
from io import BytesIO
import bleach
from arabic_reshaper import ArabicReshaper
from bidi.algorithm import get_display
from django.conf import settings
from django.contrib.staticfiles import finders
from django.dispatch import receiver
from django.utils.formats import date_format
from django.utils.html import escape
from django.utils.html import conditional_escape
from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _
from PyPDF2 import PdfFileReader
@@ -32,6 +33,7 @@ from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfgen.canvas import Canvas
from reportlab.platypus import Paragraph
from pretix.base.i18n import language
from pretix.base.invoice import ThumbnailingImageReader
from pretix.base.models import Order, OrderPosition
from pretix.base.settings import PERSON_NAME_SCHEMES
@@ -61,32 +63,32 @@ DEFAULT_VARIABLES = OrderedDict((
("item", {
"label": _("Product name"),
"editor_sample": _("Sample product"),
"evaluate": lambda orderposition, order, event: escape(str(orderposition.item.name))
"evaluate": lambda orderposition, order, event: str(orderposition.item.name)
}),
("variation", {
"label": _("Variation name"),
"editor_sample": _("Sample variation"),
"evaluate": lambda op, order, event: escape(str(op.variation) if op.variation else '')
"evaluate": lambda op, order, event: str(op.variation) if op.variation else ''
}),
("item_description", {
"label": _("Product description"),
"editor_sample": _("Sample product description"),
"evaluate": lambda orderposition, order, event: escape(str(orderposition.item.description))
"evaluate": lambda orderposition, order, event: str(orderposition.item.description)
}),
("itemvar", {
"label": _("Product name and variation"),
"editor_sample": _("Sample product sample variation"),
"evaluate": lambda orderposition, order, event: escape((
"evaluate": lambda orderposition, order, event: (
'{} - {}'.format(orderposition.item.name, orderposition.variation)
if orderposition.variation else str(orderposition.item.name)
))
)
}),
("item_category", {
"label": _("Product category"),
"editor_sample": _("Ticket category"),
"evaluate": lambda orderposition, order, event: escape((
"evaluate": lambda orderposition, order, event: (
str(orderposition.item.category.name) if orderposition.item.category else ""
))
)
}),
("price", {
"label": _("Price"),
@@ -105,12 +107,12 @@ DEFAULT_VARIABLES = OrderedDict((
("attendee_name", {
"label": _("Attendee name"),
"editor_sample": _("John Doe"),
"evaluate": lambda op, order, ev: escape(op.attendee_name or (op.addon_to.attendee_name if op.addon_to else ''))
"evaluate": lambda op, order, ev: op.attendee_name or (op.addon_to.attendee_name if op.addon_to else '')
}),
("event_name", {
"label": _("Event name"),
"editor_sample": _("Sample event name"),
"evaluate": lambda op, order, ev: escape(str(ev.name))
"evaluate": lambda op, order, ev: str(ev.name)
}),
("event_date", {
"label": _("Event date"),
@@ -186,22 +188,27 @@ DEFAULT_VARIABLES = OrderedDict((
("event_location", {
"label": _("Event location"),
"editor_sample": _("Random City"),
"evaluate": lambda op, order, ev: str(ev.location).replace("\n", "<br/>\n")
"evaluate": lambda op, order, ev: str(ev.location)
}),
("invoice_name", {
"label": _("Invoice address name"),
"editor_sample": _("John Doe"),
"evaluate": lambda op, order, ev: escape(order.invoice_address.name if getattr(order, 'invoice_address', None) else '')
"evaluate": lambda op, order, ev: order.invoice_address.name if getattr(order, 'invoice_address', None) else ''
}),
("invoice_company", {
"label": _("Invoice address company"),
"editor_sample": _("Sample company"),
"evaluate": lambda op, order, ev: escape(order.invoice_address.company if getattr(order, 'invoice_address', None) else '')
"evaluate": lambda op, order, ev: order.invoice_address.company if getattr(order, 'invoice_address', None) else ''
}),
("invoice_city", {
"label": _("Invoice address city"),
"editor_sample": _("Sample city"),
"evaluate": lambda op, order, ev: order.invoice_address.city if getattr(order, 'invoice_address', None) else ''
}),
("addons", {
"label": _("List of Add-Ons"),
"editor_sample": _("Addon 1\nAddon 2"),
"evaluate": lambda op, order, ev: "<br/>".join([
"evaluate": lambda op, order, ev: "\n".join([
'{} - {}'.format(p.item, p.variation) if p.variation else str(p.item)
for p in (
op.addons.all() if 'addons' in getattr(op, '_prefetched_objects_cache', {})
@@ -213,7 +220,7 @@ DEFAULT_VARIABLES = OrderedDict((
("organizer", {
"label": _("Organizer name"),
"editor_sample": _("Event organizer company"),
"evaluate": lambda op, order, ev: escape(str(order.event.organizer.name))
"evaluate": lambda op, order, ev: str(order.event.organizer.name)
}),
("organizer_info_text", {
"label": _("Organizer info text"),
@@ -293,7 +300,7 @@ def variables_from_questions(sender, *args, **kwargs):
if not a:
return ""
else:
return escape(str(a)).replace("\n", "<br/>\n")
return str(a)
d = {}
for q in sender.questions.all():
@@ -306,11 +313,13 @@ def variables_from_questions(sender, *args, **kwargs):
def _get_attendee_name_part(key, op, order, ev):
return escape(op.attendee_name_parts.get(key, ''))
if isinstance(key, tuple):
return ' '.join(p for p in [_get_attendee_name_part(c[0], op, order, ev) for c in key] if p)
return op.attendee_name_parts.get(key, '')
def _get_ia_name_part(key, op, order, ev):
return escape(order.invoice_address.name_parts.get(key, '') if getattr(order, 'invoice_address', None) else '')
return order.invoice_address.name_parts.get(key, '') if getattr(order, 'invoice_address', None) else ''
def get_variables(event):
@@ -323,6 +332,13 @@ def get_variables(event):
'editor_sample': scheme['sample'][key],
'evaluate': partial(_get_attendee_name_part, key)
}
for i in range(2, len(scheme['fields']) + 1):
for comb in itertools.combinations(scheme['fields'], i):
v['attendee_name_%s' % ('_'.join(c[0] for c in comb))] = {
'label': _("Attendee name: {part}").format(part=' + '.join(str(c[1]) for c in comb)),
'editor_sample': ' '.join(str(scheme['sample'][c[0]]) for c in comb),
'evaluate': partial(_get_attendee_name_part, comb)
}
v['invoice_name']['editor_sample'] = scheme['concatenation'](scheme['sample'])
v['attendee_name']['editor_sample'] = scheme['concatenation'](scheme['sample'])
@@ -405,12 +421,16 @@ class Renderer:
def _get_ev(self, op, order):
return op.subevent or order.event
def _get_text_content(self, op: OrderPosition, order: Order, o: dict):
def _get_text_content(self, op: OrderPosition, order: Order, o: dict, inner=False):
if o.get('locale', None) and not inner:
with language(o['locale']):
return self._get_text_content(op, order, o, True)
ev = self._get_ev(op, order)
if not o['content']:
return '(error)'
if o['content'] == 'other':
return o['text'].replace("\n", "<br/>\n")
return o['text']
elif o['content'].startswith('meta:'):
return ev.meta_data.get(o['content'][5:]) or ''
elif o['content'] in self.variables:
@@ -442,20 +462,37 @@ class Renderer:
textColor=Color(o['color'][0] / 255, o['color'][1] / 255, o['color'][2] / 255),
alignment=align_map[o['align']]
)
text = re.sub(
"<br[^>]*>", "<br/>",
bleach.clean(
self._get_text_content(op, order, o) or "",
tags=["br"], attributes={}, styles=[], strip=True
)
)
text = conditional_escape(
self._get_text_content(op, order, o) or "",
).replace("\n", "<br/>\n")
# reportlab does not support RTL, ligature-heavy scripts like Arabic. Therefore, we use ArabicReshaper
# to resolve all ligatures and python-bidi to switch RTL texts.
configuration = {
'delete_harakat': True,
'support_ligatures': False,
}
reshaper = ArabicReshaper(configuration=configuration)
text = "<br/>".join(get_display(reshaper.reshape(l)) for l in text.split("<br/>"))
p = Paragraph(text, style=style)
p.wrapOn(canvas, float(o['width']) * mm, 1000 * mm)
w, h = p.wrapOn(canvas, float(o['width']) * mm, 1000 * mm)
# p_size = p.wrap(float(o['width']) * mm, 1000 * mm)
ad = getAscentDescent(font, float(o['fontsize']))
p.drawOn(canvas, float(o['left']) * mm, float(o['bottom']) * mm - ad[1])
canvas.saveState()
# The ascent/descent offsets here are not really proven to be correct, they're just empirical values to get
# reportlab render similarly to browser canvas.
if o.get('downward', False):
canvas.translate(float(o['left']) * mm, float(o['bottom']) * mm)
canvas.rotate(o.get('rotation', 0) * -1)
p.drawOn(canvas, 0, -h - ad[1] / 2)
else:
canvas.translate(float(o['left']) * mm, float(o['bottom']) * mm + h)
canvas.rotate(o.get('rotation', 0) * -1)
p.drawOn(canvas, 0, -h - ad[1])
canvas.restoreState()
def draw_page(self, canvas: Canvas, order: Order, op: OrderPosition):
def draw_page(self, canvas: Canvas, order: Order, op: OrderPosition, show_page=True):
for o in self.layout:
if o['type'] == "barcodearea":
self._draw_barcodearea(canvas, op, o)
@@ -465,7 +502,8 @@ class Renderer:
self._draw_poweredby(canvas, op, o)
if self.bg_pdf:
canvas.setPageSize((self.bg_pdf.getPage(0).mediaBox[2], self.bg_pdf.getPage(0).mediaBox[3]))
canvas.showPage()
if show_page:
canvas.showPage()
def render_background(self, buffer, title=_('Ticket')):
if settings.PDFTK:

View File

@@ -1,3 +1,4 @@
import os
import sys
from enum import Enum
from typing import List
@@ -44,13 +45,14 @@ def get_all_plugins(event=None) -> List[type]:
class PluginConfig(AppConfig):
IGNORE = False
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if not hasattr(self, 'PretixPluginMeta'):
raise ImproperlyConfigured("A pretix plugin config should have a PretixPluginMeta inner class.")
if hasattr(self.PretixPluginMeta, 'compatibility'):
if hasattr(self.PretixPluginMeta, 'compatibility') and not os.environ.get("PRETIX_IGNORE_CONFLICTS") == "True":
import pkg_resources
try:
pkg_resources.require(self.PretixPluginMeta.compatibility)

View File

@@ -8,6 +8,7 @@ from django import forms
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
BASE_CHOICES = (
('date_from', _('Event start')),
@@ -115,6 +116,8 @@ class RelativeDateWrapper:
base_date_name=parts[3],
time=time
)
if data.base_date_name not in [k[0] for k in BASE_CHOICES]:
raise ValueError('{} is not a valid base date'.format(data.base_date_name))
else:
data = parser.parse(input)
return RelativeDateWrapper(data)
@@ -330,3 +333,39 @@ class ModelRelativeDateTimeField(models.CharField):
defaults = {'form_class': self.form_class}
defaults.update(kwargs)
return super().formfield(**defaults)
class SerializerRelativeDateField(serializers.CharField):
def to_internal_value(self, data):
if data is None:
return None
try:
r = RelativeDateWrapper.from_string(data)
if isinstance(r.data, RelativeDate):
if r.data.time is not None:
raise ValidationError("Do not specify a time for a date field")
return r
except:
raise ValidationError("Invalid relative date")
def to_representation(self, value: RelativeDateWrapper):
if value is None:
return None
return value.to_string()
class SerializerRelativeDateTimeField(serializers.CharField):
def to_internal_value(self, data):
if data is None:
return None
try:
return RelativeDateWrapper.from_string(data)
except:
raise ValidationError("Invalid relative date")
def to_representation(self, value: RelativeDateWrapper):
if value is None:
return None
return value.to_string()

View File

@@ -15,7 +15,7 @@ from django_scopes import scopes_disabled
from pretix.base.channels import get_all_sales_channels
from pretix.base.i18n import language
from pretix.base.models import (
CartPosition, Event, InvoiceAddress, Item, ItemBundle, ItemVariation, Seat,
CartPosition, Event, InvoiceAddress, Item, ItemVariation, Seat,
SeatCategoryMapping, Voucher,
)
from pretix.base.models.event import SubEvent
@@ -82,6 +82,9 @@ error_messages = {
'voucher_expired': _('This voucher is expired.'),
'voucher_invalid_item': _('This voucher is not valid for this product.'),
'voucher_invalid_seat': _('This voucher is not valid for this seat.'),
'voucher_no_match': _('We did not find any position in your cart that we could use this voucher for. If you want '
'to add something new to your cart using that voucher, you can do so with the voucher '
'redemption option on the bottom of the page.'),
'voucher_item_not_available': _(
'Your voucher is valid for a product that is currently not for sale.'),
'voucher_invalid_subevent': pgettext_lazy('subevent', 'This voucher is not valid for this event date.'),
@@ -105,12 +108,15 @@ error_messages = {
class CartManager:
AddOperation = namedtuple('AddOperation', ('count', 'item', 'variation', 'price', 'voucher', 'quotas',
'addon_to', 'subevent', 'includes_tax', 'bundled', 'seat'))
'addon_to', 'subevent', 'includes_tax', 'bundled', 'seat',
'price_before_voucher'))
RemoveOperation = namedtuple('RemoveOperation', ('position',))
VoucherOperation = namedtuple('VoucherOperation', ('position', 'voucher', 'price'))
ExtendOperation = namedtuple('ExtendOperation', ('position', 'count', 'item', 'variation', 'price', 'voucher',
'quotas', 'subevent', 'seat'))
'quotas', 'subevent', 'seat', 'price_before_voucher'))
order = {
RemoveOperation: 10,
VoucherOperation: 15,
ExtendOperation: 20,
AddOperation: 30
}
@@ -228,7 +234,7 @@ class CartManager:
# TODO: i18n plurals
raise CartError(_(error_messages['max_items']) % (self.event.settings.max_items_per_order,))
def _check_item_constraints(self, op):
def _check_item_constraints(self, op, current_ops=[]):
if isinstance(op, self.AddOperation) or isinstance(op, self.ExtendOperation):
if not (
(isinstance(op, self.AddOperation) and op.addon_to == 'FAKE') or
@@ -271,7 +277,7 @@ class CartManager:
raise CartError(error_messages['ended'])
seated = self._is_seated(op.item, op.subevent)
if seated and (not op.seat or op.seat.blocked):
if seated and (not op.seat or (op.seat.blocked and self._sales_channel not in self.event.settings.seating_allow_blocked_seats_for_channel)):
raise CartError(error_messages['seat_invalid'])
elif op.seat and not seated:
raise CartError(error_messages['seat_forbidden'])
@@ -300,10 +306,10 @@ class CartManager:
if op.item.max_per_order or op.item.min_per_order:
new_total = (
len([1 for p in self.positions if p.item_id == op.item.pk]) +
sum([_op.count for _op in self._operations
sum([_op.count for _op in self._operations + current_ops
if isinstance(_op, self.AddOperation) and _op.item == op.item]) +
op.count -
len([1 for _op in self._operations
len([1 for _op in self._operations + current_ops
if isinstance(_op, self.RemoveOperation) and _op.position.item_id == op.item.pk])
)
@@ -364,10 +370,10 @@ class CartManager:
cp.item.requires_seat = cp.requires_seat
if cp.is_bundled:
try:
bundle = cp.addon_to.item.bundles.get(bundled_item=cp.item, bundled_variation=cp.variation)
bundle = cp.addon_to.item.bundles.filter(bundled_item=cp.item, bundled_variation=cp.variation).first()
if bundle:
price = bundle.designated_price or 0
except ItemBundle.DoesNotExist:
else:
price = cp.price
changed_prices[cp.pk] = price
@@ -379,6 +385,7 @@ class CartManager:
else:
price = self._get_price(cp.item, cp.variation, cp.voucher, price, cp.subevent,
force_custom_price=True)
pbv = TAXED_ZERO
else:
bundled_sum = Decimal('0.00')
if not cp.addon_to_id:
@@ -391,9 +398,14 @@ class CartManager:
price = self._get_price(cp.item, cp.variation, cp.voucher, cp.price, cp.subevent,
cp_is_net=True, bundled_sum=bundled_sum)
price = TaxedPrice(net=price.net, gross=price.net, rate=0, tax=0, name='')
pbv = self._get_price(cp.item, cp.variation, None, cp.price, cp.subevent,
cp_is_net=True, bundled_sum=bundled_sum)
pbv = TaxedPrice(net=pbv.net, gross=pbv.net, rate=0, tax=0, name='')
else:
price = self._get_price(cp.item, cp.variation, cp.voucher, cp.price, cp.subevent,
bundled_sum=bundled_sum)
pbv = self._get_price(cp.item, cp.variation, None, cp.price, cp.subevent,
bundled_sum=bundled_sum)
quotas = list(cp.quotas)
if not quotas:
@@ -409,7 +421,7 @@ class CartManager:
op = self.ExtendOperation(
position=cp, item=cp.item, variation=cp.variation, voucher=cp.voucher, count=1,
price=price, quotas=quotas, subevent=cp.subevent, seat=cp.seat
price=price, quotas=quotas, subevent=cp.subevent, seat=cp.seat, price_before_voucher=pbv
)
self._check_item_constraints(op)
@@ -419,6 +431,60 @@ class CartManager:
self._operations.append(op)
return err
def apply_voucher(self, voucher_code: str):
if self._operations:
raise CartError('Applying a voucher to the whole cart should not be combined with other operations.')
try:
voucher = self.event.vouchers.get(code__iexact=voucher_code.strip())
except Voucher.DoesNotExist:
raise CartError(error_messages['voucher_invalid'])
voucher_use_diff = Counter()
ops = []
if not voucher.is_active():
raise CartError(error_messages['voucher_expired'])
for p in self.positions:
if p.voucher_id:
continue
if not voucher.applies_to(p.item, p.variation):
continue
if voucher.seat and voucher.seat != p.seat:
continue
if voucher.subevent_id and voucher.subevent_id != p.subevent_id:
continue
if p.is_bundled:
continue
bundled_sum = Decimal('0.00')
if not p.addon_to_id:
for bundledp in p.addons.all():
if bundledp.is_bundled:
bundledprice = bundledp.price
bundled_sum += bundledprice
price = self._get_price(p.item, p.variation, voucher, None, p.subevent, bundled_sum=bundled_sum)
"""
if price.gross > p.price:
continue
"""
voucher_use_diff[voucher] += 1
ops.append((p.price - price.gross, self.VoucherOperation(p, voucher, price)))
# If there are not enough voucher usages left for the full cart, let's apply them in the order that benefits
# the user the most.
ops.sort(key=lambda k: k[0], reverse=True)
self._operations += [k[1] for k in ops]\
if not voucher_use_diff:
raise CartError(error_messages['voucher_no_match'])
self._voucher_use_diff += voucher_use_diff
def add_new_items(self, items: List[dict]):
# Fetch items from the database
self._update_items_cache([i['item'] for i in items], [i['variation'] for i in items])
@@ -429,7 +495,7 @@ class CartManager:
for i in items:
if self.event.has_subevents:
if not i.get('subevent'):
if not i.get('subevent') or int(i.get('subevent')) not in self._subevents_cache:
raise CartError(error_messages['subevent_required'])
subevent = self._subevents_cache[int(i.get('subevent'))]
else:
@@ -510,18 +576,20 @@ class CartManager:
bop = self.AddOperation(
count=bundle.count, item=bitem, variation=bvar, price=bprice,
voucher=None, quotas=bundle_quotas, addon_to='FAKE', subevent=subevent,
includes_tax=bool(bprice.rate), bundled=[], seat=None
includes_tax=bool(bprice.rate), bundled=[], seat=None, price_before_voucher=bprice,
)
self._check_item_constraints(bop)
self._check_item_constraints(bop, operations)
bundled.append(bop)
price = self._get_price(item, variation, voucher, i.get('price'), subevent, bundled_sum=bundled_sum)
pbv = self._get_price(item, variation, None, i.get('price'), subevent, bundled_sum=bundled_sum)
op = self.AddOperation(
count=i['count'], item=item, variation=variation, price=price, voucher=voucher, quotas=quotas,
addon_to=False, subevent=subevent, includes_tax=bool(price.rate), bundled=bundled, seat=seat
addon_to=False, subevent=subevent, includes_tax=bool(price.rate), bundled=bundled, seat=seat,
price_before_voucher=pbv
)
self._check_item_constraints(op)
self._check_item_constraints(op, operations)
operations.append(op)
self._quota_diff.update(quota_diff)
@@ -625,9 +693,10 @@ class CartManager:
op = self.AddOperation(
count=1, item=item, variation=variation, price=price, voucher=None, quotas=quotas,
addon_to=cp, subevent=cp.subevent, includes_tax=bool(price.rate), bundled=[], seat=None
addon_to=cp, subevent=cp.subevent, includes_tax=bool(price.rate), bundled=[], seat=None,
price_before_voucher=None
)
self._check_item_constraints(op)
self._check_item_constraints(op, operations)
operations.append(op)
# Check constraints on the add-on combinations
@@ -762,7 +831,7 @@ class CartManager:
self._operations.sort(key=lambda a: self.order[type(a)])
seats_seen = set()
for op in self._operations:
for iop, op in enumerate(self._operations):
if isinstance(op, self.RemoveOperation):
if op.position.expires > self.now_dt:
for q in op.position.quotas:
@@ -830,7 +899,7 @@ class CartManager:
available_count = 0
if isinstance(op, self.AddOperation):
if op.seat and not op.seat.is_available(ignore_voucher_id=op.voucher.id if op.voucher else None):
if op.seat and not op.seat.is_available(ignore_voucher_id=op.voucher.id if op.voucher else None, sales_channel=self._sales_channel):
available_count = 0
err = err or error_messages['seat_unavailable']
@@ -839,7 +908,8 @@ class CartManager:
event=self.event, item=op.item, variation=op.variation,
price=op.price.gross, expires=self._expiry, cart_id=self.cart_id,
voucher=op.voucher, addon_to=op.addon_to if op.addon_to else None,
subevent=op.subevent, includes_tax=op.includes_tax, seat=op.seat
subevent=op.subevent, includes_tax=op.includes_tax, seat=op.seat,
price_before_voucher=op.price_before_voucher.gross if op.price_before_voucher is not None else None
)
if self.event.settings.attendee_names_asked:
scheme = PERSON_NAME_SCHEMES.get(self.event.settings.name_scheme)
@@ -878,7 +948,7 @@ class CartManager:
new_cart_positions.append(cp)
elif isinstance(op, self.ExtendOperation):
if op.seat and not op.seat.is_available(ignore_cart=op.position,
if op.seat and not op.seat.is_available(ignore_cart=op.position, sales_channel=self._sales_channel,
ignore_voucher_id=op.position.voucher_id):
err = err or error_messages['seat_unavailable']
op.position.addons.all().delete()
@@ -886,6 +956,8 @@ class CartManager:
elif available_count == 1:
op.position.expires = self._expiry
op.position.price = op.price.gross
if op.price_before_voucher is not None:
op.position.price_before_voucher = op.price_before_voucher.gross
try:
op.position.save(force_update=True)
except DatabaseError:
@@ -896,6 +968,20 @@ class CartManager:
op.position.delete()
else:
raise AssertionError("ExtendOperation cannot affect more than one item")
elif isinstance(op, self.VoucherOperation):
if vouchers_ok[op.voucher] < 1:
if iop == 0:
raise CartError(error_messages['voucher_redeemed'])
else:
# We fail silently if we could only apply the voucher to part of the cart, since that might
# be expected
continue
op.position.price_before_voucher = op.position.price
op.position.price = op.price.gross
op.position.voucher = op.voucher
op.position.save()
vouchers_ok[op.voucher] -= 1
for p in new_cart_positions:
if getattr(p, '_answers', None):
@@ -1061,7 +1147,27 @@ def add_items_to_cart(self, event: int, items: List[dict], cart_id: str=None, lo
@app.task(base=ProfiledEventTask, bind=True, max_retries=5, default_retry_delay=1, throws=(CartError,))
def remove_cart_position(self, event: Event, position: int, cart_id: str=None, locale='en') -> None:
def apply_voucher(self, event: Event, voucher: str, cart_id: str=None, locale='en', sales_channel='web') -> None:
"""
Removes a list of items from a user's cart.
:param event: The event ID in question
:param voucher: A voucher code
:param session: Session ID of a guest
"""
with language(locale):
try:
try:
cm = CartManager(event=event, cart_id=cart_id, sales_channel=sales_channel)
cm.apply_voucher(voucher)
cm.commit()
except LockTimeoutException:
self.retry()
except (MaxRetriesExceededError, LockTimeoutException):
raise CartError(error_messages['busy'])
@app.task(base=ProfiledEventTask, bind=True, max_retries=5, default_retry_delay=1, throws=(CartError,))
def remove_cart_position(self, event: Event, position: int, cart_id: str=None, locale='en', sales_channel='web') -> None:
"""
Removes a list of items from a user's cart.
:param event: The event ID in question
@@ -1071,7 +1177,7 @@ def remove_cart_position(self, event: Event, position: int, cart_id: str=None, l
with language(locale):
try:
try:
cm = CartManager(event=event, cart_id=cart_id)
cm = CartManager(event=event, cart_id=cart_id, sales_channel=sales_channel)
cm.remove_item(position)
cm.commit()
except LockTimeoutException:
@@ -1081,7 +1187,7 @@ def remove_cart_position(self, event: Event, position: int, cart_id: str=None, l
@app.task(base=ProfiledEventTask, bind=True, max_retries=5, default_retry_delay=1, throws=(CartError,))
def clear_cart(self, event: Event, cart_id: str=None, locale='en') -> None:
def clear_cart(self, event: Event, cart_id: str=None, locale='en', sales_channel='web') -> None:
"""
Removes a list of items from a user's cart.
:param event: The event ID in question
@@ -1090,7 +1196,7 @@ def clear_cart(self, event: Event, cart_id: str=None, locale='en') -> None:
with language(locale):
try:
try:
cm = CartManager(event=event, cart_id=cart_id)
cm = CartManager(event=event, cart_id=cart_id, sales_channel=sales_channel)
cm.clear()
cm.commit()
except LockTimeoutException:

View File

@@ -7,7 +7,7 @@ from django.utils.translation import ugettext as _
from pretix.base.models import (
Checkin, CheckinList, Order, OrderPosition, Question, QuestionOption,
)
from pretix.base.signals import order_placed
from pretix.base.signals import checkin_created, order_placed
class CheckInError(Exception):
@@ -143,6 +143,7 @@ def perform_checkin(op: OrderPosition, clist: CheckinList, given_answers: dict,
'datetime': dt,
'list': clist.pk
}, user=user, auth=auth)
checkin_created.send(op.order.event, checkin=ci)
else:
if not force:
raise CheckInError(
@@ -171,4 +172,5 @@ def order_placed(sender, **kwargs):
for op in order.positions.all():
for cl in cls:
if cl.all_products or op.item_id in {i.pk for i in cl.limit_products.all()}:
Checkin.objects.create(position=op, list=cl, auto_checked_in=True)
ci = Checkin.objects.create(position=op, list=cl, auto_checked_in=True)
checkin_created.send(event, checkin=ci)

View File

@@ -13,6 +13,7 @@ from django.db import transaction
from django.db.models import Count
from django.dispatch import receiver
from django.utils import timezone
from django.utils.formats import date_format
from django.utils.timezone import now
from django.utils.translation import pgettext, ugettext as _
from django_countries.fields import Country
@@ -52,11 +53,17 @@ def build_invoice(invoice: Invoice) -> Invoice:
footer = invoice.event.settings.get('invoice_footer_text', as_type=LazyI18nString)
if lp and lp.payment_provider:
if 'payment' in inspect.signature(lp.payment_provider.render_invoice_text).parameters:
payment = lp.payment_provider.render_invoice_text(invoice.order, lp)
payment = str(lp.payment_provider.render_invoice_text(invoice.order, lp))
else:
payment = lp.payment_provider.render_invoice_text(invoice.order)
payment = str(lp.payment_provider.render_invoice_text(invoice.order))
else:
payment = ""
if invoice.event.settings.invoice_include_expire_date and invoice.order.status == Order.STATUS_PENDING:
if payment:
payment += "<br />"
payment += pgettext("invoice", "Please complete your payment before {expire_date}.").format(
expire_date=date_format(invoice.order.expires, "SHORT_DATE_FORMAT")
)
invoice.introductory_text = str(introductory).replace('\n', '<br />')
invoice.additional_text = str(additional).replace('\n', '<br />')

View File

@@ -3,6 +3,7 @@ import logging
import os
import re
import smtplib
import ssl
import warnings
from email.mime.image import MIMEImage
from email.utils import formataddr
@@ -132,7 +133,7 @@ def mail(email: str, subject: str, template: Union[str, LazyI18nString],
else:
sender = formataddr((settings.PRETIX_INSTANCE_NAME, sender))
subject = str(subject)
subject = raw_subject = str(subject)
signature = ""
bcc = []
@@ -198,13 +199,13 @@ def mail(email: str, subject: str, template: Union[str, LazyI18nString],
try:
if 'position' in inspect.signature(renderer.render).parameters:
body_html = renderer.render(content_plain, signature, str(subject), order, position)
body_html = renderer.render(content_plain, signature, raw_subject, order, position)
else:
# Backwards compatibility
warnings.warn('E-mail renderer called without position argument because position argument is not '
'supported.',
DeprecationWarning)
body_html = renderer.render(content_plain, signature, str(subject), order)
body_html = renderer.render(content_plain, signature, raw_subject, order)
except:
logger.exception('Could not render HTML body')
body_html = None
@@ -365,6 +366,8 @@ def mail_send_task(self, *args, to: List[str], subject: str, body: str, html: st
raise SendMailException('Failed to send an email to {}.'.format(to))
except Exception as e:
if isinstance(e, (smtplib.SMTPServerDisconnected, smtplib.SMTPConnectError, ssl.SSLError, OSError)):
self.retry(max_retries=5, countdown=2 ** (self.request.retries * 2))
if order:
order.log_action(
'pretix.event.order.email.error',

View File

@@ -0,0 +1,173 @@
import csv
import io
from decimal import Decimal
from django.core.exceptions import ValidationError
from django.db import transaction
from django.utils.timezone import now
from django.utils.translation import gettext as _
from pretix.base.i18n import LazyLocaleException, language
from pretix.base.models import (
CachedFile, Event, InvoiceAddress, Order, OrderPayment, OrderPosition,
User,
)
from pretix.base.orderimport import get_all_columns
from pretix.base.services.invoices import generate_invoice, invoice_qualified
from pretix.base.services.tasks import ProfiledEventTask
from pretix.base.signals import order_paid, order_placed
from pretix.celery_app import app
class DataImportError(LazyLocaleException):
def __init__(self, *args):
msg = args[0]
msgargs = args[1] if len(args) > 1 else None
self.args = args
if msgargs:
msg = _(msg) % msgargs
else:
msg = _(msg)
super().__init__(msg)
def parse_csv(file, length=None):
data = file.read(length)
try:
import chardet
charset = chardet.detect(data)['encoding']
except ImportError:
charset = file.charset
data = data.decode(charset or 'utf-8')
# If the file was modified on a Mac, it only contains \r as line breaks
if '\r' in data and '\n' not in data:
data = data.replace('\r', '\n')
dialect = csv.Sniffer().sniff(data.split("\n")[0], delimiters=";,.#:")
if dialect is None:
return None
reader = csv.DictReader(io.StringIO(data), dialect=dialect)
return reader
def setif(record, obj, attr, setting):
if setting.startswith('csv:'):
setattr(obj, attr, record[setting[4:]] or '')
@app.task(base=ProfiledEventTask, throws=(DataImportError,))
def import_orders(event: Event, fileid: str, settings: dict, locale: str, user) -> None:
# TODO: quotacheck?
cf = CachedFile.objects.get(id=fileid)
user = User.objects.get(pk=user)
with language(locale):
cols = get_all_columns(event)
parsed = parse_csv(cf.file)
orders = []
order = None
data = []
# Run validation
for i, record in enumerate(parsed):
values = {}
for c in cols:
val = c.resolve(settings, record)
try:
values[c.identifier] = c.clean(val, values)
except ValidationError as e:
raise DataImportError(
_(
'Error while importing value "{value}" for column "{column}" in line "{line}": {message}').format(
value=val if val is not None else '', column=c.verbose_name, line=i + 1, message=e.message
)
)
data.append(values)
# Prepare model objects. Yes, this might consume lots of RAM, but allows us to make the actual SQL transaction
# shorter. We'll see what works better in reality…
for i, record in enumerate(data):
try:
if order is None or settings['orders'] == 'many':
order = Order(
event=event,
testmode=settings['testmode'],
)
order.meta_info = {}
order._positions = []
order._address = InvoiceAddress()
order._address.name_parts = {'_scheme': event.settings.name_scheme}
orders.append(order)
position = OrderPosition()
position.attendee_name_parts = {'_scheme': event.settings.name_scheme}
position.meta_info = {}
order._positions.append(position)
position.assign_pseudonymization_id()
for c in cols:
c.assign(record.get(c.identifier), order, position, order._address)
except ImportError as e:
raise ImportError(
_('Invalid data in row {row}: {message}').format(row=i, message=str(e))
)
# quota check?
with event.lock():
with transaction.atomic():
for o in orders:
o.total = sum([c.price for c in o._positions]) # currently no support for fees
if o.total == Decimal('0.00'):
o.status = Order.STATUS_PAID
o.save()
OrderPayment.objects.create(
local_id=1,
order=o,
amount=Decimal('0.00'),
provider='free',
info='{}',
payment_date=now(),
state=OrderPayment.PAYMENT_STATE_CONFIRMED
)
elif settings['status'] == 'paid':
o.status = Order.STATUS_PAID
o.save()
OrderPayment.objects.create(
local_id=1,
order=o,
amount=o.total,
provider='manual',
info='{}',
payment_date=now(),
state=OrderPayment.PAYMENT_STATE_CONFIRMED
)
else:
o.status = Order.STATUS_PENDING
o.save()
for p in o._positions:
p.order = o
p.save()
o._address.order = o
o._address.save()
for c in cols:
c.save(o)
o.log_action(
'pretix.event.order.placed',
user=user,
data={'source': 'import'}
)
for o in orders:
with language(o.locale):
order_placed.send(event, order=o)
if o.status == Order.STATUS_PAID:
order_paid.send(event, order=o)
gen_invoice = invoice_qualified(o) and (
(event.settings.get('invoice_generate') == 'True') or
(event.settings.get('invoice_generate') == 'paid' and o.status == Order.STATUS_PAID)
) and not o.invoices.last()
if gen_invoice:
generate_invoice(o, trigger_pdf=True)
cf.delete()

View File

@@ -11,6 +11,7 @@ from django.core.cache import cache
from django.db import transaction
from django.db.models import Exists, F, Max, Min, OuterRef, Q, Sum
from django.db.models.functions import Coalesce, Greatest
from django.db.transaction import get_connection
from django.dispatch import receiver
from django.utils.functional import cached_property
from django.utils.timezone import make_aware, now
@@ -70,6 +71,8 @@ error_messages = {
'voucher_invalid': _('The voucher code used for one of the items in your cart is not known in our database.'),
'voucher_redeemed': _('The voucher code used for one of the items in your cart has already been used the maximum '
'number of times allowed. We removed this item from your cart.'),
'voucher_budget_used': _('The voucher code used for one of the items in your cart has already been too often. We '
'adjusted the price of the item in your cart.'),
'voucher_expired': _('The voucher code used for one of the items in your cart is expired. We removed this item '
'from your cart.'),
'voucher_invalid_item': _('The voucher code used for one of the items in your cart is not valid for this item. We '
@@ -290,9 +293,10 @@ def _cancel_order(order, user=None, send_mail: bool=True, api_token=None, device
if not order.cancel_allowed():
raise OrderError(_('You cannot cancel this order.'))
invoices = []
i = order.invoices.filter(is_cancellation=False, refered__isnull=True).last()
if i:
generate_cancellation(i)
invoices.append(generate_cancellation(i))
for position in order.positions.all():
for gc in position.issued_gift_cards.all():
@@ -334,7 +338,7 @@ def _cancel_order(order, user=None, send_mail: bool=True, api_token=None, device
order.save(update_fields=['status', 'total'])
if i:
generate_invoice(order)
invoices.append(generate_invoice(order))
else:
with order.event.lock():
order.status = Order.STATUS_CANCELED
@@ -355,7 +359,8 @@ def _cancel_order(order, user=None, send_mail: bool=True, api_token=None, device
try:
order.send_mail(
email_subject, email_template, email_context,
'pretix.event.order.email.order_canceled', user
'pretix.event.order.email.order_canceled', user,
invoices=invoices if order.event.settings.invoice_email_attachment else []
)
except SendMailException:
logger.exception('Order canceled email could not be sent')
@@ -418,13 +423,15 @@ def _check_date(event: Event, now_dt: datetime):
raise OrderError(error_messages['ended'])
def _check_positions(event: Event, now_dt: datetime, positions: List[CartPosition], address: InvoiceAddress=None):
def _check_positions(event: Event, now_dt: datetime, positions: List[CartPosition], address: InvoiceAddress=None,
sales_channel='web'):
err = None
errargs = None
_check_date(event, now_dt)
products_seen = Counter()
changed_prices = {}
v_budget = {}
deleted_positions = set()
seats_seen = set()
@@ -467,6 +474,20 @@ def _check_positions(event: Event, now_dt: datetime, positions: List[CartPositio
delete(cp)
continue
if cp.voucher.budget is not None:
if cp.voucher not in v_budget:
v_budget[cp.voucher] = cp.voucher.budget - cp.voucher.budget_used()
disc = cp.price_before_voucher - cp.price
if disc > v_budget[cp.voucher]:
new_disc = max(0, v_budget[cp.voucher])
cp.price = cp.price + (disc - new_disc)
cp.save()
err = err or error_messages['voucher_budget_used']
v_budget[cp.voucher] -= new_disc
continue
else:
v_budget[cp.voucher] -= disc
if cp.subevent and cp.subevent.presale_start and now_dt < cp.subevent.presale_start:
err = err or error_messages['some_subevent_not_started']
delete(cp)
@@ -512,7 +533,7 @@ def _check_positions(event: Event, now_dt: datetime, positions: List[CartPositio
if cp.seat:
# Unlike quotas (which we blindly trust as long as the position is not expired), we check seats every
# time, since we absolutely can not overbook a seat.
if not cp.seat.is_available(ignore_cart=cp, ignore_voucher_id=cp.voucher_id) or cp.seat.blocked:
if not cp.seat.is_available(ignore_cart=cp, ignore_voucher_id=cp.voucher_id, sales_channel=sales_channel):
err = err or error_messages['seat_unavailable']
cp.delete()
continue
@@ -521,6 +542,11 @@ def _check_positions(event: Event, now_dt: datetime, positions: List[CartPositio
# Other checks are not necessary
continue
max_discount = None
if cp.price_before_voucher is not None and cp.voucher in v_budget:
current_discount = cp.price_before_voucher - cp.price
max_discount = max(v_budget[cp.voucher] + current_discount, 0)
if cp.is_bundled:
try:
bundle = cp.addon_to.item.bundles.get(bundled_item=cp.item, bundled_variation=cp.variation)
@@ -528,7 +554,9 @@ def _check_positions(event: Event, now_dt: datetime, positions: List[CartPositio
except ItemBundle.DoesNotExist:
bprice = cp.price
price = get_price(cp.item, cp.variation, cp.voucher, bprice, cp.subevent, custom_price_is_net=False,
invoice_address=address, force_custom_price=True)
invoice_address=address, force_custom_price=True, max_discount=max_discount)
pbv = get_price(cp.item, cp.variation, None, bprice, cp.subevent, custom_price_is_net=False,
invoice_address=address, force_custom_price=True, max_discount=max_discount)
changed_prices[cp.pk] = bprice
else:
bundled_sum = 0
@@ -538,7 +566,14 @@ def _check_positions(event: Event, now_dt: datetime, positions: List[CartPositio
bundled_sum += changed_prices.get(bundledp.pk, bundledp.price)
price = get_price(cp.item, cp.variation, cp.voucher, cp.price, cp.subevent, custom_price_is_net=False,
addon_to=cp.addon_to, invoice_address=address, bundled_sum=bundled_sum)
addon_to=cp.addon_to, invoice_address=address, bundled_sum=bundled_sum,
max_discount=max_discount)
pbv = get_price(cp.item, cp.variation, None, cp.price, cp.subevent, custom_price_is_net=False,
addon_to=cp.addon_to, invoice_address=address, bundled_sum=bundled_sum,
max_discount=max_discount)
if max_discount is not None:
v_budget[cp.voucher] = v_budget[cp.voucher] + current_discount - (pbv.gross - price.gross)
if price is False or len(quotas) == 0:
err = err or error_messages['unavailable']
@@ -551,6 +586,11 @@ def _check_positions(event: Event, now_dt: datetime, positions: List[CartPositio
delete(cp)
continue
if pbv is not None and pbv.gross != price.gross:
cp.price_before_voucher = pbv.gross
else:
cp.price_before_voucher = None
if price.gross != cp.price and not (cp.item.free_price and cp.price > price.gross):
cp.price = price.gross
cp.includes_tax = bool(price.rate)
@@ -801,12 +841,15 @@ def _perform_order(event: Event, payment_provider: str, position_ids: List[str],
lockfn = event.lock
with lockfn() as now_dt:
positions = list(positions.select_related('item', 'variation', 'subevent', 'seat', 'addon_to').prefetch_related('addons'))
positions = list(
positions.select_related('item', 'variation', 'subevent', 'seat', 'addon_to').prefetch_related('addons')
)
positions.sort(key=lambda k: position_ids.index(k.pk))
if len(positions) == 0:
raise OrderError(error_messages['empty'])
if len(position_ids) != len(positions):
raise OrderError(error_messages['internal'])
_check_positions(event, now_dt, positions, address=addr)
_check_positions(event, now_dt, positions, address=addr, sales_channel=sales_channel)
order, payment = _create_order(event, email, positions, now_dt, pprov,
locale=locale, address=addr, meta_info=meta_info, sales_channel=sales_channel,
gift_cards=gift_cards, shown_total=shown_total)
@@ -944,7 +987,7 @@ def send_download_reminders(sender, **kwargs):
continue
reminder_date = (o.first_date - timedelta(days=days)).replace(hour=0, minute=0, second=0, microsecond=0)
if now() < reminder_date:
if now() < reminder_date or o.datetime > reminder_date:
continue
with transaction.atomic():
@@ -991,7 +1034,7 @@ def send_download_reminders(sender, **kwargs):
logger.exception('Reminder email could not be sent to attendee')
def notify_user_changed_order(order, user=None, auth=None):
def notify_user_changed_order(order, user=None, auth=None, invoices=[]):
with language(order.locale):
email_template = order.event.settings.mail_text_order_changed
email_context = get_email_context(event=order.event, order=order)
@@ -999,7 +1042,7 @@ def notify_user_changed_order(order, user=None, auth=None):
try:
order.send_mail(
email_subject, email_template, email_context,
'pretix.event.order.email.order_changed', user, auth=auth
'pretix.event.order.email.order_changed', user, auth=auth, invoices=invoices,
)
except SendMailException:
logger.exception('Order changed email could not be sent')
@@ -1049,6 +1092,7 @@ class OrderChangeManager:
self._operations = []
self.notify = notify
self._invoice_dirty = False
self._invoices = []
def change_item(self, position: OrderPosition, item: Item, variation: Optional[ItemVariation]):
if (not variation and item.has_variations) or (variation and variation.item_id != item.pk):
@@ -1064,6 +1108,21 @@ class OrderChangeManager:
self._operations.append(self.ItemOperation(position, item, variation))
def change_seat(self, position: OrderPosition, seat: Seat):
if isinstance(seat, str):
subev = None
if self.event.has_subevents:
subev = position.subevent
for p in self._operations:
if isinstance(p, self.SubeventOperation) and p.position == position:
subev = p.subevent
try:
seat = Seat.objects.get(
event=self.event,
subevent=subev,
seat_guid=seat
)
except Seat.DoesNotExist:
raise OrderError(error_messages['seat_invalid'])
if position.seat:
self._seatdiff.subtract([position.seat])
if seat:
@@ -1147,6 +1206,19 @@ class OrderChangeManager:
def add_position(self, item: Item, variation: ItemVariation, price: Decimal, addon_to: Order = None,
subevent: SubEvent = None, seat: Seat = None):
if isinstance(seat, str):
if not seat:
seat = None
else:
try:
seat = Seat.objects.get(
event=self.event,
subevent=subevent,
seat_guid=seat
)
except Seat.DoesNotExist:
raise OrderError(error_messages['seat_invalid'])
if price is None:
price = get_price(item, variation, subevent=subevent, invoice_address=self._invoice_address)
else:
@@ -1170,7 +1242,7 @@ class OrderChangeManager:
raise OrderError(self.error_messages['seat_required'])
elif not seated and seat:
raise OrderError(self.error_messages['seat_forbidden'])
if seat and subevent and seat.subevent_id != subevent:
if seat and subevent and seat.subevent_id != subevent.pk:
raise OrderError(self.error_messages['seat_subevent_mismatch'].format(seat=seat.name))
new_quotas = (variation.quotas.filter(subevent=subevent)
@@ -1197,7 +1269,7 @@ class OrderChangeManager:
for seat, diff in self._seatdiff.items():
if diff <= 0:
continue
if not seat.is_available() or diff > 1:
if not seat.is_available(sales_channel=self.order.sales_channel) or diff > 1:
raise OrderError(self.error_messages['seat_unavailable'].format(seat=seat.name))
if self.event.has_subevents:
@@ -1333,6 +1405,16 @@ class OrderChangeManager:
op.position.item = op.item
op.position.variation = op.variation
op.position._calculate_tax()
if op.position.price_before_voucher is not None and op.position.voucher and not op.position.addon_to_id:
op.position.price_before_voucher = max(
op.position.price,
get_price(
op.position.item, op.position.variation,
subevent=op.position.subevent,
custom_price=op.position.price,
invoice_address=self._invoice_address
).gross
)
op.position.save()
elif isinstance(op, self.SeatOperation):
self.order.log_action('pretix.event.order.changed.seat', user=self.user, auth=self.auth, data={
@@ -1356,6 +1438,16 @@ class OrderChangeManager:
})
op.position.subevent = op.subevent
op.position.save()
if op.position.price_before_voucher is not None and op.position.voucher and not op.position.addon_to_id:
op.position.price_before_voucher = max(
op.position.price,
get_price(
op.position.item, op.position.variation,
subevent=op.position.subevent,
custom_price=op.position.price,
invoice_address=self._invoice_address
).gross
)
elif isinstance(op, self.FeeValueOperation):
self.order.log_action('pretix.event.order.changed.feevalue', user=self.user, auth=self.auth, data={
'fee': op.fee.pk,
@@ -1617,8 +1709,8 @@ class OrderChangeManager:
def _reissue_invoice(self):
i = self.order.invoices.filter(is_cancellation=False).last()
if self.reissue_invoice and i and self._invoice_dirty:
generate_cancellation(i)
generate_invoice(self.order)
self._invoices.append(generate_cancellation(i))
self._invoices.append(generate_invoice(self.order))
def _check_complete_cancel(self):
current = self.order.positions.count()
@@ -1664,9 +1756,15 @@ class OrderChangeManager:
self._check_paid_to_free()
if self.notify:
notify_user_changed_order(self.order, self.user, self.auth)
notify_user_changed_order(
self.order, self.user, self.auth,
self._invoices if self.event.settings.invoice_email_attachment else []
)
if self.split_order:
notify_user_changed_order(self.split_order, self.user, self.auth)
notify_user_changed_order(
self.split_order, self.user, self.auth,
list(self.split_order.invoices.all()) if self.event.settings.invoice_email_attachment else []
)
order_changed.send(self.order.event, order=self.order)
@@ -1766,6 +1864,9 @@ def cancel_order(self, order: int, user: int=None, send_mail: bool=True, api_tok
def change_payment_provider(order: Order, payment_provider, amount=None, new_payment=None, create_log=True,
recreate_invoices=True):
if not get_connection().in_atomic_block:
raise Exception('change_payment_provider should only be called in atomic transaction!')
oldtotal = order.total
e = OrderPayment.objects.filter(fee=OuterRef('pk'), state__in=(OrderPayment.PAYMENT_STATE_CONFIRMED,
OrderPayment.PAYMENT_STATE_REFUNDED))
@@ -1786,34 +1887,32 @@ def change_payment_provider(order: Order, payment_provider, amount=None, new_pay
new_fee = payment_provider.calculate_fee(
order.pending_sum - old_fee if amount is None else amount
)
with transaction.atomic():
if new_fee:
fee.value = new_fee
fee.internal_type = payment_provider.identifier
fee._calculate_tax()
fee.save()
else:
if fee.pk:
fee.delete()
fee = None
if new_fee:
fee.value = new_fee
fee.internal_type = payment_provider.identifier
fee._calculate_tax()
fee.save()
else:
if fee.pk:
fee.delete()
fee = None
open_payment = None
if new_payment:
lp = order.payments.exclude(pk=new_payment.pk).last()
lp = order.payments.select_for_update().exclude(pk=new_payment.pk).last()
else:
lp = order.payments.last()
if lp and lp.state not in (OrderPayment.PAYMENT_STATE_CONFIRMED, OrderPayment.PAYMENT_STATE_REFUNDED):
lp = order.payments.select_for_update().last()
if lp and lp.state in (OrderPayment.PAYMENT_STATE_PENDING, OrderPayment.PAYMENT_STATE_CREATED):
open_payment = lp
if open_payment and open_payment.state in (OrderPayment.PAYMENT_STATE_PENDING,
OrderPayment.PAYMENT_STATE_CREATED):
if open_payment:
try:
with transaction.atomic():
open_payment.payment_provider.cancel_payment(open_payment)
order.log_action('pretix.event.order.payment.canceled', {
'local_id': open_payment.local_id,
'provider': open_payment.provider,
})
open_payment.payment_provider.cancel_payment(open_payment)
order.log_action('pretix.event.order.payment.canceled', {
'local_id': open_payment.local_id,
'provider': open_payment.provider,
})
except PaymentException as e:
order.log_action(
'pretix.event.order.payment.canceled.failed',

View File

@@ -12,7 +12,8 @@ def get_price(item: Item, variation: ItemVariation = None,
voucher: Voucher = None, custom_price: Decimal = None,
subevent: SubEvent = None, custom_price_is_net: bool = False,
addon_to: AbstractPosition = None, invoice_address: InvoiceAddress = None,
force_custom_price: bool = False, bundled_sum: Decimal = Decimal('0.00')) -> TaxedPrice:
force_custom_price: bool = False, bundled_sum: Decimal = Decimal('0.00'),
max_discount: Decimal = None) -> TaxedPrice:
if addon_to:
try:
iao = addon_to.item.addons.get(addon_category_id=item.category_id)
@@ -32,7 +33,7 @@ def get_price(item: Item, variation: ItemVariation = None,
price = subevent.var_price_overrides[variation.pk]
if voucher:
price = voucher.calculate_price(price)
price = voucher.calculate_price(price, max_discount=max_discount)
if item.tax_rule:
tax_rule = item.tax_rule

View File

@@ -65,6 +65,8 @@ def generate_seats(event, subevent, plan, mapping):
update(seat, 'seat_number', ss.number),
update(seat, 'zone_name', ss.zone),
update(seat, 'sorting_rank', ss.sorting_rank),
update(seat, 'row_label', ss.row_label),
update(seat, 'seat_label', ss.seat_label),
])
if updated:
seat.save()
@@ -78,6 +80,8 @@ def generate_seats(event, subevent, plan, mapping):
seat_number=ss.number,
zone_name=ss.zone,
sorting_rank=ss.sorting_rank,
row_label=ss.row_label,
seat_label=ss.seat_label,
product=p,
))

File diff suppressed because it is too large Load Diff

View File

@@ -405,6 +405,17 @@ the deletion of the order.
As with all event-plugin signals, the ``sender`` keyword argument will contain the event.
"""
checkin_created = EventPluginSignal(
providing_args=["checkin"],
)
"""
This signal is sent out every time a check-in is created (i.e. an order position is marked as
checked in). It is not send if the position was already checked in and is force-checked-in a second time.
The check-in object is given as the first argument
As with all event-plugin signals, the ``sender`` keyword argument will contain the event.
"""
logentry_display = EventPluginSignal(
providing_args=["logentry"]
)
@@ -630,3 +641,38 @@ invoice_line_text = EventPluginSignal(
This signal is sent out when an invoice is built for an order. You can return additional text that
should be shown on the invoice for the given ``position``.
"""
order_import_columns = EventPluginSignal(
providing_args=[]
)
"""
This signal is sent out if the user performs an import of orders from an external source. You can use this
to define additional columns that can be read during import. You are expected to return a list of instances of
``ImportColumn`` subclasses.
As with all event-plugin signals, the ``sender`` keyword argument will contain the event.
"""
validate_event_settings = EventPluginSignal(
providing_args=["settings_dict"]
)
"""
This signal is sent out if the user performs an update of event settings through the API or web interface.
You are passed a ``settings_dict`` dictionary with the new state of the event settings object and are expected
to raise a ``django.core.exceptions.ValidationError`` if the new state is not valid.
You can not modify the dictionary. This is only recommended to use if you have multiple settings
that can only be validated together. To validate individual settings, pass a validator to the
serializer field instead.
As with all event-plugin signals, the ``sender`` keyword argument will contain the event.
"""
api_event_settings_fields = EventPluginSignal(
providing_args=[]
)
"""
This signal is sent out to collect serializable settings fields for the API. You are expected to
return a dictionary mapping names of attributes in the settings store to DRF serializer field instances.
As with all event-plugin signals, the ``sender`` keyword argument will contain the event.
"""

View File

@@ -139,6 +139,14 @@
text-decoration: none;
color: {{ color }};
}
{% if rtl %}
body {
direction: rtl;
}
.content table td {
text-align: right;
}
{% endif %}
{% block addcss %}{% endblock %}
</style>

View File

@@ -0,0 +1,275 @@
{% load eventurl %}
{% load i18n %}
{% load thumb %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=false">
<style type="text/css">
body {
background-color: #eee;
background-position: top;
background-repeat: repeat-x;
font-family: "Open Sans", "OpenSans", "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
line-height: 20px;
color: #333;
margin: 0;
padding-top: 20px;
}
table.layout > tr > td {
background-color: white;
padding: 0;
}
table.layout > tr > td.header {
padding: 0 20px;
text-align: center;
}
.header h2 {
margin-top: 20px;
margin-bottom: 10px;
font-size: 22px;
line-height: 26px;
}
.header h1 {
margin-top: 0;
margin-bottom: 20px;
font-size: 26px;
line-height: 30px;
}
.header h2 a, .header h1 a, .content h2 a, .content h3 a {
text-decoration: none;
}
.content h2, .content h3 {
margin-bottom: 20px;
margin-top: 10px;
}
a {
color: {{ color }};
font-weight: bold;
}
a:hover, a:focus {
color: {{ color }};
text-decoration: underline;
}
a:hover, a:active {
outline: 0;
}
p {
margin: 0 0 10px;
/* These are technically the same, but use both */
overflow-wrap: break-word;
word-wrap: break-word;
-ms-word-break: break-all;
/* This is the dangerous one in WebKit, as it breaks things wherever */
word-break: break-all;
/* Instead use this non-standard one: */
word-break: break-word;
/* Adds a hyphen where the word breaks, if supported (No Blink) */
-ms-hyphens: auto;
-moz-hyphens: auto;
-webkit-hyphens: auto;
hyphens: auto;
}
p:last-child {
margin-bottom: 0;
}
.footer {
padding: 10px;
text-align: center;
font-size: 12px;
}
.content {
padding: 0 18px;
}
::selection {
background: {{ color }};
color: #FFF;
}
table.layout {
width: 100%;
max-width: 600px;
border-spacing: 0px;
border-collapse: separate;
margin: auto;
}
img.wide {
width: 100%;
height: auto;
}
.content table {
width: 100%;
}
.content table td {
vertical-align: top;
text-align: left;
}
table.layout > tr > td.containertd {
padding: 15px 0;
}
a.button {
display: inline-block;
padding: 10px 16px;
font-size: 14px;
line-height: 1.33333;
border: 1px solid #cccccc;
border-radius: 6px;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
margin: 5px;
text-decoration: none;
color: {{ color }};
}
{% if rtl %}
body {
direction: rtl;
}
.content table td {
text-align: right;
}
{% endif %}
{% block addcss %}{% endblock %}
</style>
<!--[if mso]>
<style type="text/css">
body, table, td {
font-family: "Open Sans", "OpenSans", "Helvetica Neue", Helvetica, Arial, sans-serif !important;
}
</style>
<![endif]-->
</head>
<body align="center">
<!--[if gte mso 9]>
<table width="100%"><tr><td align="center">
<table width="600"><tr><td align="center"
<![endif]-->
<table class="layout" width="600" border="0" cellspacing="0">
{% if event.settings.logo_image %}
<!--[if !mso]><!-- -->
<tr>
<td style="line-height: 0" align="center">
{% if event.settings.logo_image|thumb:'5000x120'|first == '/' %}
<img src="{{ site_url }}{{ event.settings.logo_image|thumb:'5000x120' }}" alt="{{ event.name }}"
style="height: auto; max-width: 100%;" />
{% else %}
<img src="{{ event.settings.logo_image|thumb:'5000x120' }}" alt="{{ event.name }}"
style="height: auto; max-width: 100%;" />
{% endif %}
</td>
</tr>
<!--<![endif]-->
{% endif %}
<tr>
<td class="header" align="center">
<!--[if gte mso 9]>
<table cellpadding="20"><tr><td align="center">
<![endif]-->
{% if event %}
<h2><a href="{% abseventurl event "presale:event.index" %}" target="_blank">{{ event.name }}</a>
</h2>
{% else %}
<h2><a href="{{ site_url }}" target="_blank">{{ site }}</a></h2>
{% endif %}
{% block header %}
<h1>{{ subject }}</h1>
{% endblock %}
<!--[if gte mso 9]>
</td></tr></table>
<![endif]-->
</td>
</tr>
<tr>
<td class="containertd">
<!--[if gte mso 9]>
<table cellpadding="20"><tr><td>
<![endif]-->
<div class="content">
{{ body|safe }}
</div>
<!--[if gte mso 9]>
</td></tr></table>
<![endif]-->
</td>
</tr>
{% if order %}
<tr>
<td class="order containertd">
<!--[if gte mso 9]>
<table cellpadding="20"><tr><td>
<![endif]-->
<div class="content">
{% if position %}
{% trans "You are receiving this email because someone signed you up for the following event:" %}<br>
<strong>{% trans "Event:" %}</strong> {{ event.name }}<br>
<strong>{% trans "Order code:" %}</strong> {{ order.code }}<br>
<strong>{% trans "Order date:" %}</strong> {{ order.datetime|date:"SHORT_DATE_FORMAT" }}<br>
<a href="{% abseventurl event "presale:event.order.position" order=order.code secret=position.web_secret position=position.positionid %}">
{% trans "View registration details" %}
</a>
{% else %}
{% trans "You are receiving this email because you placed an order for the following event:" %}<br>
<strong>{% trans "Event:" %}</strong> {{ event.name }}<br>
<strong>{% trans "Order code:" %}</strong> {{ order.code }}<br>
<strong>{% trans "Order date:" %}</strong> {{ order.datetime|date:"SHORT_DATE_FORMAT" }}<br>
<a href="{% abseventurl event "presale:event.order.open" hash=order.email_confirm_hash order=order.code secret=order.secret %}">
{% trans "View order details" %}
</a>
{% endif %}
</div>
<!--[if gte mso 9]>
</td></tr></table>
<![endif]-->
</td>
</tr>
{% endif %}
{% if signature %}
<tr>
<td class="order containertd">
<!--[if gte mso 9]>
<table cellpadding="20"><tr><td>
<![endif]-->
<div class="content">
{{ signature | safe }}
</div>
<!--[if gte mso 9]>
</td></tr></table>
<![endif]-->
</td>
</tr>
{% endif %}
</table>
<div class="footer">
{% include "pretixbase/email/email_footer.html" %}
</div>
<br/>
<br/>
<!--[if gte mso 9]>
</td></tr></table>
</td></tr></table>
<![endif]-->
</body>
</html>

View File

@@ -175,6 +175,11 @@ def timeline_for_event(event, subevent=None):
for pprov in pprovs.values():
if not pprov.settings.get('_enabled', as_type=bool):
continue
try:
if not pprov.is_enabled:
continue
except:
pass
availability_date = pprov.settings.get('_availability_date', as_type=RelativeDateWrapper)
if availability_date:
d = make_aware(datetime.combine(

View File

@@ -23,7 +23,11 @@ class AsyncAction:
if not isinstance(self.task, app.Task):
raise TypeError('Method has no task attached')
res = self.task.apply_async(args=args, kwargs=kwargs)
try:
res = self.task.apply_async(args=args, kwargs=kwargs)
except ConnectionError:
# Task very likely not yet sent, due to redis restarting etc. Let's try once agan
res = self.task.apply_async(args=args, kwargs=kwargs)
if 'ajax' in self.request.GET or 'ajax' in self.request.POST:
data = self._return_ajax_result(res)
@@ -60,6 +64,14 @@ class AsyncAction:
res.get(timeout=timeout, propagate=False)
except celery.exceptions.TimeoutError:
pass
except ConnectionError:
# Redis probably just restarted, let's just report not ready and retry next time
data = self._ajax_response_data()
data.update({
'async_id': res.id,
'ready': False
})
return data
ready = res.ready()
data = self._ajax_response_data()

View File

@@ -79,7 +79,7 @@ class ClearableBasenameFileInput(forms.ClearableFileInput):
@property
def is_img(self):
return any(self.file.name.endswith(e) for e in ('.jpg', '.jpeg', '.png', '.gif'))
return any(self.file.name.lower().endswith(e) for e in ('.jpg', '.jpeg', '.png', '.gif'))
def __str__(self):
return os.path.basename(self.file.name).split('.', 1)[-1]

View File

@@ -1,6 +1,7 @@
from urllib.parse import urlencode
from django import forms
from django.conf import settings
from django.contrib.auth.hashers import check_password
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator, validate_email
from django.db.models import Q
@@ -9,10 +10,8 @@ from django.urls import reverse
from django.utils.html import escape
from django.utils.safestring import mark_safe
from django.utils.timezone import get_current_timezone_name
from django.utils.translation import (
pgettext, pgettext_lazy, ugettext_lazy as _,
)
from django_countries import Countries, countries
from django.utils.translation import pgettext_lazy, ugettext_lazy as _
from django_countries import Countries
from django_countries.fields import LazyTypedChoiceField
from i18nfield.forms import (
I18nForm, I18nFormField, I18nFormSetMixin, I18nTextarea, I18nTextInput,
@@ -25,10 +24,12 @@ from pretix.base.forms import I18nModelForm, PlaceholderValidator, SettingsForm
from pretix.base.models import Event, Organizer, TaxRule, Team
from pretix.base.models.event import EventMetaValue, SubEvent
from pretix.base.reldate import RelativeDateField, RelativeDateTimeField
from pretix.base.settings import PERSON_NAME_SCHEMES, PERSON_NAME_TITLE_GROUPS
from pretix.base.settings import (
PERSON_NAME_SCHEMES, PERSON_NAME_TITLE_GROUPS, validate_settings,
)
from pretix.control.forms import (
ExtFileField, FontSelect, MultipleLanguagesWidget, SingleLanguageWidget,
SlugWidget, SplitDateTimeField, SplitDateTimePickerWidget,
ExtFileField, FontSelect, MultipleLanguagesWidget, SlugWidget,
SplitDateTimeField, SplitDateTimePickerWidget,
)
from pretix.control.forms.widgets import Select2
from pretix.multidomain.urlreverse import build_absolute_uri
@@ -146,7 +147,8 @@ class EventWizardBasicsForm(I18nModelForm):
self.user = kwargs.pop('user')
kwargs.pop('session')
super().__init__(*args, **kwargs)
self.initial['timezone'] = get_current_timezone_name()
if 'timezone' not in self.initial:
self.initial['timezone'] = get_current_timezone_name()
self.fields['locale'].choices = [(a, b) for a, b in settings.LANGUAGES if a in self.locales]
self.fields['location'].widget.attrs['rows'] = '3'
self.fields['location'].widget.attrs['placeholder'] = _(
@@ -270,12 +272,18 @@ class EventMetaValueForm(forms.ModelForm):
super().__init__(*args, **kwargs)
self.fields['value'].required = False
self.fields['value'].widget.attrs['placeholder'] = self.property.default
self.fields['value'].widget.attrs['data-typeahead-url'] = (
reverse('control:events.meta.typeahead') + '?' + urlencode({
'property': self.property.name,
'organizer': self.property.organizer.slug,
})
)
class Meta:
model = EventMetaValue
fields = ['value']
widgets = {
'value': forms.TextInput
'value': forms.TextInput()
}
@@ -330,94 +338,10 @@ class EventUpdateForm(I18nModelForm):
class EventSettingsForm(SettingsForm):
show_date_to = forms.BooleanField(
label=_("Show event end date"),
help_text=_("If disabled, only event's start date will be displayed to the public."),
required=False
)
show_times = forms.BooleanField(
label=_("Show dates with time"),
help_text=_("If disabled, the event's start and end date will be displayed without the time of day."),
required=False
)
show_items_outside_presale_period = forms.BooleanField(
label=_("Show items outside presale period"),
help_text=_("Show item details before presale has started and after presale has ended"),
required=False
)
display_net_prices = forms.BooleanField(
label=_("Show net prices instead of gross prices in the product list (not recommended!)"),
help_text=_("Independent of your choice, the cart will show gross prices as this is the price that needs to be "
"paid"),
required=False
)
presale_start_show_date = forms.BooleanField(
label=_("Show start date"),
help_text=_("Show the presale start date before presale has started."),
widget=forms.CheckboxInput,
required=False
)
last_order_modification_date = RelativeDateTimeField(
label=_('Last date of modifications'),
help_text=_("The last date users can modify details of their orders, such as attendee names or "
"answers to questions. If you use the event series feature and an order contains tickets for "
"multiple event dates, the earliest date will be used."),
required=False,
)
timezone = forms.ChoiceField(
choices=((a, a) for a in common_timezones),
label=_("Event timezone"),
)
locales = forms.MultipleChoiceField(
choices=settings.LANGUAGES,
widget=MultipleLanguagesWidget,
label=_("Available languages"),
)
locale = forms.ChoiceField(
choices=settings.LANGUAGES,
widget=SingleLanguageWidget,
label=_("Default language"),
)
show_quota_left = forms.BooleanField(
label=_("Show number of tickets left"),
help_text=_("Publicly show how many tickets of a certain type are still available."),
required=False
)
waiting_list_enabled = forms.BooleanField(
label=_("Enable waiting list"),
help_text=_("Once a ticket is sold out, people can add themselves to a waiting list. As soon as a ticket "
"becomes available again, it will be reserved for the first person on the waiting list and this "
"person will receive an email notification with a voucher that can be used to buy a ticket."),
required=False
)
waiting_list_hours = forms.IntegerField(
label=_("Waiting list response time"),
min_value=6,
help_text=_("If a ticket voucher is sent to a person on the waiting list, it has to be redeemed within this "
"number of hours until it expires and can be re-assigned to the next person on the list."),
required=False,
widget=forms.NumberInput(),
)
waiting_list_auto = forms.BooleanField(
label=_("Automatic waiting list assignments"),
help_text=_("If ticket capacity becomes free, automatically create a voucher and send it to the first person "
"on the waiting list for that product. If this is not active, mails will not be send automatically "
"but you can send them manually via the control panel. If you disable the waiting list but keep "
"this option enabled, tickets will still be sent out."),
required=False,
widget=forms.CheckboxInput(),
)
attendee_names_asked = forms.BooleanField(
label=_("Ask for attendee names"),
help_text=_("Ask for a name for all tickets which include admission to the event."),
required=False,
)
attendee_names_required = forms.BooleanField(
label=_("Require attendee names"),
help_text=_("Require customers to fill in the names of all attendees."),
required=False,
widget=forms.CheckboxInput(attrs={'data-checkbox-dependency': '#id_settings-attendee_names_asked'}),
)
name_scheme = forms.ChoiceField(
label=_("Name format"),
help_text=_("This defines how pretix will ask for human names. Changing this after you already received "
@@ -430,83 +354,6 @@ class EventSettingsForm(SettingsForm):
"restrict the set of selectable titles."),
required=False,
)
attendee_emails_asked = forms.BooleanField(
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 admission 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 E-mail settings."),
required=False
)
attendee_emails_required = forms.BooleanField(
label=_("Require email addresses per ticket"),
help_text=_("Require customers to fill in individual e-mail addresses for all admission tickets. See the "
"above option for more details. One email address for the order confirmation will always be "
"required regardless of this setting."),
required=False,
widget=forms.CheckboxInput(attrs={'data-checkbox-dependency': '#id_settings-attendee_emails_asked'}),
)
order_email_asked_twice = forms.BooleanField(
label=_("Ask for the order email address twice"),
help_text=_("Require customers to fill in the primary email address twice to avoid errors."),
required=False,
)
max_items_per_order = forms.IntegerField(
min_value=1,
label=_("Maximum number of items per order"),
help_text=_("Add-on products will not be counted.")
)
reservation_time = forms.IntegerField(
min_value=0,
label=_("Reservation period"),
help_text=_("The number of minutes the items in a user's cart are reserved for this user."),
)
imprint_url = forms.URLField(
label=_("Imprint URL"),
help_text=_("This should point e.g. to a part of your website that has your contact details and legal "
"information."),
required=False,
)
confirm_text = I18nFormField(
label=_('Confirmation text'),
help_text=_('This text needs to be confirmed by the user before a purchase is possible. You could for example '
'link your terms of service here. If you use the Pages feature to publish your terms of service, '
'you don\'t need this setting since you can configure it there.'),
required=False,
widget=I18nTextarea
)
contact_mail = forms.EmailField(
label=_("Contact address"),
required=False,
help_text=_("We'll show this publicly to allow attendees to contact you.")
)
show_variations_expanded = forms.BooleanField(
label=_("Show variations of a product expanded by default"),
required=False
)
hide_sold_out = forms.BooleanField(
label=_("Hide all products that are sold out"),
required=False
)
meta_noindex = forms.BooleanField(
label=_('Ask search engines not to index the ticket shop'),
required=False
)
redirect_to_checkout_directly = forms.BooleanField(
label=_('Directly redirect to check-out after a product has been added to the cart.'),
required=False
)
frontpage_subevent_ordering = forms.ChoiceField(
label=pgettext('subevent', 'Date ordering'),
choices=[
('date_ascending', _('Event start time')),
('date_descending', _('Event start time (descending)')),
('name_ascending', _('Name')),
('name_descending', _('Name (descending)')),
], # When adding a new ordering, remember to also define it in the event model
)
logo_image = ExtFileField(
label=_('Logo image'),
ext_whitelist=(".png", ".jpg", ".gif", ".jpeg"),
@@ -523,33 +370,6 @@ class EventSettingsForm(SettingsForm):
'WhatsApp and Reddit only show a square preview, so we recommend to make sure it still looks good '
'only the center square is shown. If you do not fill this, we will use the logo given above.')
)
frontpage_text = I18nFormField(
label=_("Frontpage text"),
required=False,
widget=I18nTextarea
)
checkout_email_helptext = I18nFormField(
label=_("Help text of the email field"),
required=False,
widget_kwargs={'attrs': {'rows': '2'}},
widget=I18nTextarea
)
presale_has_ended_text = I18nFormField(
label=_("End of presale text"),
required=False,
widget=I18nTextarea,
widget_kwargs={'attrs': {'rows': '2'}},
help_text=_("This text will be shown above the ticket shop once the designated sales timeframe for this event "
"is over. You can use it to describe other options to get a ticket, such as a box office.")
)
voucher_explanation_text = I18nFormField(
label=_("Voucher explanation"),
required=False,
widget=I18nTextarea,
widget_kwargs={'attrs': {'rows': '2'}},
help_text=_("This text will be shown next to the input for a voucher code. You can use it e.g. to explain "
"how to obtain a voucher code.")
)
primary_color = forms.CharField(
label=_("Primary color"),
required=False,
@@ -588,24 +408,49 @@ class EventSettingsForm(SettingsForm):
help_text=_('Only respected by modern browsers.')
)
auto_fields = [
'imprint_url',
'checkout_email_helptext',
'presale_has_ended_text',
'voucher_explanation_text',
'show_date_to',
'show_times',
'show_items_outside_presale_period',
'display_net_prices',
'presale_start_show_date',
'locales',
'locale',
'show_quota_left',
'waiting_list_enabled',
'waiting_list_hours',
'waiting_list_auto',
'max_items_per_order',
'reservation_time',
'contact_mail',
'show_variations_expanded',
'hide_sold_out',
'meta_noindex',
'redirect_to_checkout_directly',
'frontpage_subevent_ordering',
'frontpage_text',
'attendee_names_asked',
'attendee_names_required',
'attendee_emails_asked',
'attendee_emails_required',
'confirm_text',
'order_email_asked_twice',
'last_order_modification_date',
]
def clean(self):
data = super().clean()
if 'locales' in data and data['locale'] not in data['locales']:
raise ValidationError({
'locale': _('Your default locale must also be enabled for your event (see box above).')
})
if data['attendee_names_required'] and not data['attendee_names_asked']:
raise ValidationError({
'attendee_names_required': _('You cannot require specifying attendee names if you do not ask for them.')
})
if data['attendee_emails_required'] and not data['attendee_emails_asked']:
raise ValidationError({
'attendee_emails_required': _('You have to ask for attendee emails if you want to make them required.')
})
settings_dict = self.event.settings.freeze()
settings_dict.update(data)
validate_settings(self.event, data)
return data
def __init__(self, *args, **kwargs):
event = kwargs['obj']
self.event = kwargs['obj']
super().__init__(*args, **kwargs)
self.fields['confirm_text'].widget.attrs['rows'] = '3'
self.fields['confirm_text'].widget.attrs['placeholder'] = _(
@@ -626,82 +471,34 @@ class EventSettingsForm(SettingsForm):
))
for k, v in PERSON_NAME_TITLE_GROUPS.items()
]
if not event.has_subevents:
if not self.event.has_subevents:
del self.fields['frontpage_subevent_ordering']
self.fields['primary_font'].choices += [
(a, a) for a in get_fonts()
(a, {"title": a, "data": v}) for a, v in get_fonts().items()
]
class CancelSettingsForm(SettingsForm):
cancel_allow_user = forms.BooleanField(
label=_("Customers can cancel their unpaid orders"),
required=False
)
cancel_allow_user_until = RelativeDateTimeField(
label=_("Do not allow cancellations after"),
required=False
)
cancel_allow_user_paid = forms.BooleanField(
label=_("Customers can cancel their paid orders"),
help_text=_("Paid money will be automatically paid back if the payment method allows it. "
"Otherwise, a manual refund will be created for you to process manually."),
required=False
)
cancel_allow_user_paid_keep = forms.DecimalField(
label=_("Keep a fixed cancellation fee"),
required=False
)
cancel_allow_user_paid_keep_fees = forms.BooleanField(
label=_("Keep payment, shipping and service fees"),
required=False
)
cancel_allow_user_paid_keep_percentage = forms.DecimalField(
label=_("Keep a percentual cancellation fee"),
required=False
)
cancel_allow_user_paid_until = RelativeDateTimeField(
label=_("Do not allow cancellations after"),
required=False
)
auto_fields = [
'cancel_allow_user',
'cancel_allow_user_until',
'cancel_allow_user_paid',
'cancel_allow_user_paid_until',
'cancel_allow_user_paid_keep',
'cancel_allow_user_paid_keep_fees',
'cancel_allow_user_paid_keep_percentage',
]
class PaymentSettingsForm(SettingsForm):
payment_term_days = forms.IntegerField(
label=_('Payment term in days'),
help_text=_("The number of days after placing an order the user has to pay to preserve their reservation. If "
"you use slow payment methods like bank transfer, we recommend 14 days. If you only use real-time "
"payment methods, we recommend still setting two or three days to allow people to retry failed "
"payments."),
)
payment_term_last = RelativeDateField(
label=_('Last date of payments'),
help_text=_("The last date any payments are accepted. This has precedence over the number of "
"days configured above. If you use the event series feature and an order contains tickets for "
"multiple dates, the earliest date will be used."),
required=False,
)
payment_term_weekdays = forms.BooleanField(
label=_('Only end payment terms on weekdays'),
help_text=_("If this is activated and the payment term of any order ends on a Saturday or Sunday, it will be "
"moved to the next Monday instead. This is required in some countries by civil law. This will "
"not effect the last date of payments configured above."),
required=False,
)
payment_term_expire_automatically = forms.BooleanField(
label=_('Automatically expire unpaid orders'),
help_text=_("If checked, all unpaid orders will automatically go from 'pending' to 'expired' "
"after the end of their payment deadline. This means that those tickets go back to "
"the pool and can be ordered by other people."),
required=False
)
payment_term_accept_late = forms.BooleanField(
label=_('Accept late payments'),
help_text=_("Accept payments for orders even when they are in 'expired' state as long as enough "
"capacity is available. No payments will ever be accepted after the 'Last date of payments' "
"configured above."),
required=False
)
auto_fields = [
'payment_term_days',
'payment_term_last',
'payment_term_weekdays',
'payment_term_expire_automatically',
'payment_term_accept_late',
'payment_explanation',
]
tax_rate_default = forms.ModelChoiceField(
queryset=TaxRule.objects.none(),
label=_('Tax rule for payment fees'),
@@ -709,27 +506,13 @@ class PaymentSettingsForm(SettingsForm):
help_text=_("The tax rule that applies for additional fees you configured for single payment methods. This "
"will set the tax rate and reverse charge rules, other settings of the tax rule are ignored.")
)
payment_explanation = I18nFormField(
widget=I18nTextarea,
widget_kwargs={'attrs': {
'rows': 3,
}},
required=False,
label=_("Guidance text"),
help_text=_("This text will be shown above the payment options. You can explain the choices to the user here, "
"if you want.")
)
def clean(self):
cleaned_data = super().clean()
payment_term_last = cleaned_data.get('payment_term_last')
if payment_term_last and self.obj.presale_end:
if payment_term_last.date(self.obj) < self.obj.presale_end.date():
self.add_error(
'payment_term_last',
_('The last payment date cannot be before the end of presale.'),
)
return cleaned_data
data = super().clean()
settings_dict = self.obj.settings.freeze()
settings_dict.update(data)
validate_settings(self.obj, data)
return data
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@@ -777,88 +560,39 @@ class ProviderForm(SettingsForm):
class InvoiceSettingsForm(SettingsForm):
allcountries = list(countries)
allcountries.insert(0, ('', _('Select country')))
invoice_address_asked = forms.BooleanField(
label=_("Ask for invoice address"),
required=False
)
invoice_address_required = forms.BooleanField(
label=_("Require invoice address"),
required=False,
widget=forms.CheckboxInput(attrs={'data-checkbox-dependency': '#id_invoice_address_asked'}),
)
invoice_address_company_required = forms.BooleanField(
label=_("Require a business addresses"),
help_text=_('This will require users to enter a company name.'),
required=False,
widget=forms.CheckboxInput(attrs={'data-checkbox-dependency': '#id_invoice_address_required'}),
)
invoice_name_required = forms.BooleanField(
label=_("Require customer name"),
required=False,
)
invoice_address_vatid = forms.BooleanField(
label=_("Ask for VAT ID"),
help_text=_("Does only work if an invoice address is asked for. VAT ID is not required."),
widget=forms.CheckboxInput(attrs={'data-checkbox-dependency': '#id_invoice_address_asked'}),
required=False
)
invoice_address_beneficiary = forms.BooleanField(
label=_("Ask for beneficiary"),
widget=forms.CheckboxInput(attrs={'data-checkbox-dependency': '#id_invoice_address_asked'}),
required=False
)
invoice_address_not_asked_free = forms.BooleanField(
label=_('Do not ask for invoice address if an order is free'),
required=False
)
invoice_include_free = forms.BooleanField(
label=_("Show free products on invoices"),
help_text=_("Note that invoices will never be generated for orders that contain only free "
"products."),
required=False
)
invoice_address_explanation_text = I18nFormField(
label=_("Invoice address explanation"),
required=False,
widget=I18nTextarea,
widget_kwargs={'attrs': {'rows': '2'}},
help_text=_("This text will be shown above the invoice address form during checkout.")
)
invoice_numbers_consecutive = forms.BooleanField(
label=_("Generate invoices with consecutive numbers"),
help_text=_("If deactivated, the order code will be used in the invoice number."),
required=False
)
invoice_numbers_prefix = forms.CharField(
label=_("Invoice number prefix"),
help_text=_("This will be prepended to invoice numbers. If you leave this field empty, your event slug will "
"be used followed by a dash. Attention: If multiple events within the same organization use the "
"same value in this field, they will share their number range, i.e. every full number will be "
"used at most once over all of your events. This setting only affects future invoices."),
required=False,
)
invoice_numbers_prefix_cancellations = forms.CharField(
label=_("Invoice number prefix for cancellations"),
help_text=_("This will be prepended to invoice numbers of cancellations. If you leave this field empty, "
"the same numbering scheme will be used that you configured for regular invoices."),
required=False,
)
invoice_generate = forms.ChoiceField(
label=_("Generate invoices"),
required=False,
widget=forms.RadioSelect,
choices=(
('False', _('Do not generate invoices')),
('admin', _('Only manually in admin panel')),
('user', _('Automatically on user request')),
('True', _('Automatically for all created orders')),
('paid', _('Automatically on payment')),
),
help_text=_("Invoices will never be automatically generated for free orders.")
)
auto_fields = [
'invoice_address_asked',
'invoice_address_required',
'invoice_address_vatid',
'invoice_address_company_required',
'invoice_address_beneficiary',
'invoice_name_required',
'invoice_address_not_asked_free',
'invoice_include_free',
'invoice_show_payments',
'invoice_reissue_after_modify',
'invoice_generate',
'invoice_attendee_name',
'invoice_include_expire_date',
'invoice_numbers_consecutive',
'invoice_numbers_prefix',
'invoice_numbers_prefix_cancellations',
'invoice_address_explanation_text',
'invoice_email_attachment',
'invoice_address_from_name',
'invoice_address_from',
'invoice_address_from_zipcode',
'invoice_address_from_city',
'invoice_address_from_country',
'invoice_address_from_tax_id',
'invoice_address_from_vat_id',
'invoice_introductory_text',
'invoice_additional_text',
'invoice_footer_text',
]
invoice_generate_sales_channels = forms.MultipleChoiceField(
label=_('Generate invoices for Sales channels'),
choices=[],
@@ -866,100 +600,11 @@ class InvoiceSettingsForm(SettingsForm):
help_text=_("If you have enabled invoice generation in the previous setting, you can limit it here to specific "
"sales channels.")
)
invoice_attendee_name = forms.BooleanField(
label=_("Show attendee names on invoices"),
required=False
)
invoice_email_attachment = forms.BooleanField(
label=_("Attach invoices to emails"),
help_text=_("If invoices are automatically generated for all orders, they will be attached to the order "
"confirmation mail. If they are automatically generated on payment, they will be attached to the "
"payment confirmation mail. If they are not automatically generated, they will not be attached "
"to emails."),
required=False
)
invoice_renderer = forms.ChoiceField(
label=_("Invoice style"),
required=True,
choices=[]
)
invoice_address_from_name = forms.CharField(
label=_("Company name"),
required=False,
)
invoice_address_from = forms.CharField(
label=_("Address line"),
widget=forms.Textarea(attrs={
'rows': 2,
'placeholder': _(
'Albert Einstein Road 52'
)
}),
required=False,
)
invoice_address_from_zipcode = forms.CharField(
widget=forms.TextInput(attrs={
'placeholder': '12345'
}),
required=False,
label=_("ZIP code"),
)
invoice_address_from_city = forms.CharField(
widget=forms.TextInput(attrs={
'placeholder': _('Random City')
}),
required=False,
label=_("City"),
)
invoice_address_from_country = forms.ChoiceField(
choices=allcountries,
required=False,
label=_("Country"),
)
invoice_address_from_tax_id = forms.CharField(
required=False,
label=_("Domestic tax ID"),
)
invoice_address_from_vat_id = forms.CharField(
required=False,
label=_("EU VAT ID"),
)
invoice_introductory_text = I18nFormField(
widget=I18nTextarea,
widget_kwargs={'attrs': {
'rows': 3,
'placeholder': _(
'e.g. With this document, we sent you the invoice for your ticket order.'
)
}},
required=False,
label=_("Introductory text"),
help_text=_("Will be printed on every invoice above the invoice rows.")
)
invoice_additional_text = I18nFormField(
widget=I18nTextarea,
widget_kwargs={'attrs': {
'rows': 3,
'placeholder': _(
'e.g. Thank you for your purchase! You can find more information on the event at ...'
)
}},
required=False,
label=_("Additional text"),
help_text=_("Will be printed on every invoice below the invoice total.")
)
invoice_footer_text = I18nFormField(
widget=I18nTextarea,
widget_kwargs={'attrs': {
'rows': 5,
'placeholder': _(
'e.g. your bank details, legal details like your VAT ID, registration numbers, etc.'
)
}},
required=False,
label=_("Footer"),
help_text=_("Will be printed centered and in a smaller font at the end of every invoice page.")
)
invoice_language = forms.ChoiceField(
widget=forms.Select, required=True,
label=_("Invoice language"),
@@ -989,6 +634,13 @@ class InvoiceSettingsForm(SettingsForm):
(c.identifier, c.verbose_name) for c in get_all_sales_channels().values()
)
def clean(self):
data = super().clean()
settings_dict = self.obj.settings.freeze()
settings_dict.update(data)
validate_settings(self.obj, data)
return data
def multimail_validate(val):
s = val.split(',')
@@ -998,22 +650,13 @@ def multimail_validate(val):
class MailSettingsForm(SettingsForm):
mail_prefix = forms.CharField(
label=_("Subject prefix"),
help_text=_("This will be prepended to the subject of all outgoing emails, formatted as [prefix]. "
"Choose, for example, a short form of your event name."),
required=False
)
mail_from = forms.EmailField(
label=_("Sender address"),
help_text=_("Sender address for outgoing emails"),
)
mail_from_name = forms.CharField(
label=_("Sender name"),
help_text=_("Sender name used in conjunction with the sender address for outgoing emails. "
"Defaults to your event name."),
required=False
)
auto_fields = [
'mail_prefix',
'mail_from',
'mail_from_name',
'mail_attach_ical',
]
mail_bcc = forms.CharField(
label=_("Bcc address"),
help_text=_("All emails will be sent to this address as a Bcc copy"),
@@ -1021,12 +664,6 @@ class MailSettingsForm(SettingsForm):
required=False,
max_length=255
)
mail_attach_ical = forms.BooleanField(
label=_("Attach calendar files"),
help_text=_("If enabled, we will attach an .ics calendar file to order confirmation emails."),
required=False
)
mail_text_signature = I18nFormField(
label=_("Signature"),
required=False,
@@ -1045,7 +682,6 @@ class MailSettingsForm(SettingsForm):
required=True,
choices=[]
)
mail_text_order_placed = I18nFormField(
label=_("Text sent to order contact address"),
required=False,
@@ -1281,30 +917,13 @@ class MailSettingsForm(SettingsForm):
class TicketSettingsForm(SettingsForm):
ticket_download = forms.BooleanField(
label=_("Use feature"),
help_text=_("Use pretix to generate tickets for the user to download and print out."),
required=False
)
ticket_download_date = RelativeDateTimeField(
label=_("Download date"),
help_text=_("Ticket download will be offered after this date. If you use the event series feature and an order "
"contains tickets for multiple event dates, download of all tickets will be available if at least "
"one of the event dates allows it."),
required=False,
)
ticket_download_addons = forms.BooleanField(
label=_("Offer to download tickets separately for add-on products"),
required=False,
)
ticket_download_nonadm = forms.BooleanField(
label=_("Generate tickets for non-admission products"),
required=False,
)
ticket_download_pending = forms.BooleanField(
label=_("Offer to download tickets even before an order is paid"),
required=False,
)
auto_fields = [
'ticket_download',
'ticket_download_date',
'ticket_download_addons',
'ticket_download_nonadm',
'ticket_download_pending',
]
def prepare_fields(self):
# See clean()
@@ -1433,14 +1052,8 @@ class WidgetCodeForm(forms.Form):
class EventDeleteForm(forms.Form):
error_messages = {
'pw_current_wrong': _("The password you entered was not correct."),
'slug_wrong': _("The slug you entered was not correct."),
}
user_pw = forms.CharField(
max_length=255,
label=_("Your password"),
widget=forms.PasswordInput()
)
slug = forms.CharField(
max_length=255,
label=_("Event slug"),
@@ -1448,19 +1061,8 @@ class EventDeleteForm(forms.Form):
def __init__(self, *args, **kwargs):
self.event = kwargs.pop('event')
self.user = kwargs.pop('user')
super().__init__(*args, **kwargs)
def clean_user_pw(self):
user_pw = self.cleaned_data.get('user_pw')
if not check_password(user_pw, self.user.password):
raise forms.ValidationError(
self.error_messages['pw_current_wrong'],
code='pw_current_wrong',
)
return user_pw
def clean_slug(self):
slug = self.cleaned_data.get('slug')
if slug != self.event.slug:

View File

@@ -440,14 +440,25 @@ class SubEventFilterForm(FilterForm):
).filter(
Q(presale_start__isnull=True) | Q(presale_start__lte=now())
).filter(
Q(presale_end__isnull=True) | Q(presale_end__gte=now())
Q(Q(presale_end__isnull=True) & Q(
Q(date_to__gte=now()) |
Q(date_to__isnull=True, date_from__gte=now())
)) |
Q(presale_end__gte=now())
)
elif fdata.get('status') == 'inactive':
qs = qs.filter(active=False)
elif fdata.get('status') == 'future':
qs = qs.filter(presale_start__gte=now())
elif fdata.get('status') == 'past':
qs = qs.filter(presale_end__lte=now())
qs = qs.filter(
Q(presale_end__lte=now()) | Q(
Q(presale_end__isnull=True) & Q(
Q(date_to__lte=now()) |
Q(date_to__isnull=True, date_from__gte=now())
)
)
)
if fdata.get('weekday'):
qs = qs.annotate(wday=ExtractWeekDay('date_from')).filter(wday=fdata.get('weekday'))
@@ -474,6 +485,8 @@ class SubEventFilterForm(FilterForm):
if fdata.get('ordering'):
qs = qs.order_by(self.get_order_by())
else:
qs = qs.order_by('-date_from')
return qs

View File

@@ -227,6 +227,18 @@ class ItemCreateForm(I18nModelForm):
super().__init__(*args, **kwargs)
self.fields['category'].queryset = self.instance.event.categories.all()
self.fields['category'].widget = Select2(
attrs={
'data-model-select2': 'generic',
'data-select2-url': reverse('control:event.items.categories.select2', kwargs={
'event': self.instance.event.slug,
'organizer': self.instance.event.organizer.slug,
}),
'data-placeholder': _('No category'),
}
)
self.fields['category'].widget.choices = self.fields['category'].choices
self.fields['tax_rule'].queryset = self.instance.event.tax_rules.all()
change_decimal_field(self.fields['default_price'], self.instance.event.currency)
self.fields['tax_rule'].empty_label = _('No taxation')
@@ -399,7 +411,6 @@ class TicketNullBooleanSelect(forms.NullBooleanSelect):
class ItemUpdateForm(I18nModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['category'].queryset = self.instance.event.categories.all()
self.fields['tax_rule'].queryset = self.instance.event.tax_rules.all()
self.fields['description'].widget.attrs['placeholder'] = _(
'e.g. This reduced price is available for full-time students, jobless and people '
@@ -431,6 +442,19 @@ class ItemUpdateForm(I18nModelForm):
self.fields['hidden_if_available'].widget.choices = self.fields['hidden_if_available'].choices
self.fields['hidden_if_available'].required = False
self.fields['category'].queryset = self.instance.event.categories.all()
self.fields['category'].widget = Select2(
attrs={
'data-model-select2': 'generic',
'data-select2-url': reverse('control:event.items.categories.select2', kwargs={
'event': self.instance.event.slug,
'organizer': self.instance.event.organizer.slug,
}),
'data-placeholder': _('No category'),
}
)
self.fields['category'].widget.choices = self.fields['category'].choices
def clean(self):
d = super().clean()
if d['issue_giftcard']:
@@ -604,6 +628,16 @@ 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'].widget = Select2(
attrs={
'data-model-select2': 'generic',
'data-select2-url': reverse('control:event.items.categories.select2', kwargs={
'event': self.event.slug,
'organizer': self.event.organizer.slug,
}),
}
)
self.fields['addon_category'].widget.choices = self.fields['addon_category'].choices
class Meta:
model = ItemAddOn
@@ -689,7 +723,7 @@ class ItemBundleForm(I18nModelForm):
def clean(self):
d = super().clean()
if not self.cleaned_data['designated_price']:
if not self.cleaned_data.get('designated_price'):
d['designated_price'] = Decimal('0.00')
self.instance.designated_price = Decimal('0.00')

View File

@@ -0,0 +1,53 @@
from django import forms
from django.utils.translation import gettext_lazy as _
from pretix.base.services.orderimport import get_all_columns
class ProcessForm(forms.Form):
orders = forms.ChoiceField(
label=_('Import mode'),
choices=(
('many', _('Create a separate order for each line')),
('one', _('Create one order with one position per line')),
)
)
status = forms.ChoiceField(
label=_('Order status'),
choices=(
('paid', _('Create orders as fully paid')),
('pending', _('Create orders as pending and still require payment')),
)
)
testmode = forms.BooleanField(
label=_('Create orders as test mode orders'),
required=False
)
def __init__(self, *args, **kwargs):
headers = kwargs.pop('headers')
initital = kwargs.pop('initial', {})
self.event = kwargs.pop('event')
initital['testmode'] = self.event.testmode
kwargs['initial'] = initital
super().__init__(*args, **kwargs)
header_choices = [
('csv:{}'.format(h), _('CSV column: "{name}"').format(name=h)) for h in headers
]
for c in get_all_columns(self.event):
choices = []
if c.default_value:
choices.append((c.default_value, c.default_label))
choices += header_choices
for k, v in c.static_choices():
choices.append(('static:{}'.format(k), v))
self.fields[c.identifier] = forms.ChoiceField(
label=str(c.verbose_name),
choices=choices,
widget=forms.Select(
attrs={'data-static': 'true'}
)
)

View File

@@ -11,9 +11,7 @@ from django.utils.translation import pgettext_lazy, ugettext_lazy as _
from pretix.base.email import get_available_placeholders
from pretix.base.forms import I18nModelForm, PlaceholderValidator
from pretix.base.forms.widgets import DatePickerWidget
from pretix.base.models import (
InvoiceAddress, ItemAddOn, Order, OrderPosition, Seat,
)
from pretix.base.models import InvoiceAddress, ItemAddOn, Order, OrderPosition
from pretix.base.models.event import SubEvent
from pretix.base.services.pricing import get_price
from pretix.control.forms.widgets import Select2
@@ -204,11 +202,10 @@ class OrderPositionAddForm(forms.Form):
required=False,
label=_('Add-on to'),
)
seat = forms.ModelChoiceField(
Seat.objects.none(),
seat = forms.CharField(
required=False,
label=_('Seat'),
empty_label=_('General admission')
widget=forms.TextInput(attrs={'placeholder': _('General admission'), 'data-seat-guid-field': 'true'}),
label=_('Seat')
)
price = forms.DecimalField(
required=False,
@@ -255,19 +252,6 @@ class OrderPositionAddForm(forms.Form):
else:
del self.fields['addon_to']
self.fields['seat'].queryset = order.event.seats.all()
self.fields['seat'].widget = Select2(
attrs={
'data-model-select2': 'seat',
'data-select2-url': reverse('control:event.seats.select2', kwargs={
'event': order.event.slug,
'organizer': order.event.organizer.slug,
}),
'data-placeholder': _('General admission')
}
)
self.fields['seat'].widget.choices = self.fields['seat'].choices
if order.event.has_subevents:
self.fields['subevent'].queryset = order.event.subevents.all()
self.fields['subevent'].widget = Select2(
@@ -318,10 +302,9 @@ class OrderPositionChangeForm(forms.Form):
required=False,
empty_label=_('(Unchanged)')
)
seat = forms.ModelChoiceField(
Seat.objects.none(),
seat = forms.CharField(
required=False,
empty_label=_('(Unchanged)')
widget=forms.TextInput(attrs={'placeholder': _('(Unchanged)'), 'data-seat-guid-field': 'true'})
)
price = forms.DecimalField(
required=False,
@@ -366,20 +349,7 @@ class OrderPositionChangeForm(forms.Form):
else:
del self.fields['subevent']
if instance.seat:
self.fields['seat'].queryset = instance.order.event.seats.all()
self.fields['seat'].widget = Select2(
attrs={
'data-model-select2': 'seat',
'data-select2-url': reverse('control:event.seats.select2', kwargs={
'event': instance.order.event.slug,
'organizer': instance.order.event.organizer.slug,
}),
'data-placeholder': _('(Unchanged)')
}
)
self.fields['seat'].widget.choices = self.fields['seat'].choices
else:
if not instance.seat:
del self.fields['seat']
choices = [

View File

@@ -302,11 +302,17 @@ class OrganizerSettingsForm(SettingsForm):
help_text=_('If you provide a favicon, we will show it instead of the default pretix icon. '
'We recommend a size of at least 200x200px to accomodate most devices.')
)
giftcard_length = forms.IntegerField(
label=_('Length of gift card codes'),
help_text=_('The system generates by default {}-character long gift card codes. However, if a different length '
'is required, it can be set here.'.format(settings.ENTROPY['giftcard_secret'])),
required=False
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['primary_font'].choices += [
(a, a) for a in get_fonts()
(a, {"title": a, "data": v}) for a, v in get_fonts().items()
]

View File

@@ -1,7 +1,9 @@
from datetime import timedelta
from urllib.parse import urlencode
from django import forms
from django.forms import formset_factory
from django.urls import reverse
from django.utils.dates import MONTHS, WEEKDAYS
from django.utils.functional import cached_property
from django.utils.timezone import now
@@ -171,6 +173,12 @@ class SubEventMetaValueForm(forms.ModelForm):
super().__init__(*args, **kwargs)
self.fields['value'].required = False
self.fields['value'].widget.attrs['placeholder'] = self.default or self.property.default
self.fields['value'].widget.attrs['data-typeahead-url'] = (
reverse('control:events.meta.typeahead') + '?' + urlencode({
'property': self.property.name,
'organizer': self.property.organizer.slug,
})
)
class Meta:
model = SubEventMetaValue

View File

@@ -38,7 +38,7 @@ class VoucherForm(I18nModelForm):
localized_fields = '__all__'
fields = [
'code', 'valid_until', 'block_quota', 'allow_ignore_quota', 'value', 'tag',
'comment', 'max_usages', 'price_mode', 'subevent', 'show_hidden_items',
'comment', 'max_usages', 'price_mode', 'subevent', 'show_hidden_items', 'budget'
]
field_classes = {
'valid_until': SplitDateTimeField,
@@ -268,7 +268,7 @@ class VoucherBulkForm(VoucherForm):
localized_fields = '__all__'
fields = [
'valid_until', 'block_quota', 'allow_ignore_quota', 'value', 'tag', 'comment',
'max_usages', 'price_mode', 'subevent', 'show_hidden_items'
'max_usages', 'price_mode', 'subevent', 'show_hidden_items', 'budget'
]
field_classes = {
'valid_until': SplitDateTimeField,
@@ -388,4 +388,9 @@ class VoucherBulkForm(VoucherForm):
del data['codes']
objs.append(obj)
Voucher.objects.bulk_create(objs)
objs = []
for v in event.vouchers.filter(code__in=self.cleaned_data['codes']):
# We need to query them again as bulk_create does not fill in .pk values on databases
# other than PostgreSQL
objs.append(v)
return objs

View File

@@ -178,6 +178,7 @@ def _display_checkin(event, logentry):
@receiver(signal=logentry_display, dispatch_uid="pretixcontrol_logentry_display")
def pretixcontrol_logentry_display(sender: Event, logentry: LogEntry, **kwargs):
plains = {
'pretix.object.cloned': _('This object has been created by cloning.'),
'pretix.event.comment': _('The event\'s internal comment has been updated.'),
'pretix.event.order.modified': _('The order details have been changed.'),
'pretix.event.order.unpaid': _('The order has been marked as unpaid.'),
@@ -324,6 +325,8 @@ def pretixcontrol_logentry_display(sender: Event, logentry: LogEntry, **kwargs):
'pretix.device.initialized': _('The device has been initialized.'),
'pretix.device.keyroll': _('The access token of the device has been regenerated.'),
'pretix.device.updated': _('The device has notified the server of an hardware or software update.'),
'pretix.giftcards.created': _('The gift card has been created.'),
'pretix.giftcards.transaction.manual': _('A manual transaction has been performed.'),
}
data = json.loads(logentry.data)

View File

@@ -169,6 +169,57 @@ def get_event_navigation(request: HttpRequest):
})
if 'can_view_orders' in request.eventpermset:
children = [
{
'label': _('All orders'),
'url': reverse('control:event.orders', kwargs={
'event': request.event.slug,
'organizer': request.event.organizer.slug,
}),
'active': url.url_name in ('event.orders', 'event.order') or "event.order." in url.url_name,
},
{
'label': _('Overview'),
'url': reverse('control:event.orders.overview', kwargs={
'event': request.event.slug,
'organizer': request.event.organizer.slug,
}),
'active': 'event.orders.overview' in url.url_name,
},
{
'label': _('Refunds'),
'url': reverse('control:event.orders.refunds', kwargs={
'event': request.event.slug,
'organizer': request.event.organizer.slug,
}),
'active': 'event.orders.refunds' in url.url_name,
},
{
'label': _('Export'),
'url': reverse('control:event.orders.export', kwargs={
'event': request.event.slug,
'organizer': request.event.organizer.slug,
}),
'active': 'event.orders.export' in url.url_name,
},
{
'label': _('Waiting list'),
'url': reverse('control:event.orders.waitinglist', kwargs={
'event': request.event.slug,
'organizer': request.event.organizer.slug,
}),
'active': 'event.orders.waitinglist' in url.url_name,
},
]
if 'can_change_orders' in request.eventpermset:
children.append({
'label': _('Import'),
'url': reverse('control:event.orders.import', kwargs={
'event': request.event.slug,
'organizer': request.event.organizer.slug,
}),
'active': 'event.orders.import' in url.url_name,
})
nav.append({
'label': _('Orders'),
'url': reverse('control:event.orders', kwargs={
@@ -177,48 +228,7 @@ def get_event_navigation(request: HttpRequest):
}),
'active': False,
'icon': 'shopping-cart',
'children': [
{
'label': _('All orders'),
'url': reverse('control:event.orders', kwargs={
'event': request.event.slug,
'organizer': request.event.organizer.slug,
}),
'active': url.url_name in ('event.orders', 'event.order') or "event.order." in url.url_name,
},
{
'label': _('Overview'),
'url': reverse('control:event.orders.overview', kwargs={
'event': request.event.slug,
'organizer': request.event.organizer.slug,
}),
'active': 'event.orders.overview' in url.url_name,
},
{
'label': _('Refunds'),
'url': reverse('control:event.orders.refunds', kwargs={
'event': request.event.slug,
'organizer': request.event.organizer.slug,
}),
'active': 'event.orders.refunds' in url.url_name,
},
{
'label': _('Export'),
'url': reverse('control:event.orders.export', kwargs={
'event': request.event.slug,
'organizer': request.event.organizer.slug,
}),
'active': 'event.orders.export' in url.url_name,
},
{
'label': _('Waiting list'),
'url': reverse('control:event.orders.waitinglist', kwargs={
'event': request.event.slug,
'organizer': request.event.organizer.slug,
}),
'active': 'event.orders.waitinglist' in url.url_name,
},
]
'children': children
})
if 'can_view_vouchers' in request.eventpermset:

View File

@@ -22,9 +22,16 @@
{% csrf_token %}
{% bootstrap_form form %}
<div class="form-group buttons">
{% if backend.login_form_fields %}
<button type="submit" class="btn btn-primary btn-block">
{% trans "Log in" %}
</button>
{% endif %}
{% if backend.url %}
<a href="{{ backend.url }}" class="btn btn-primary btn-block">
{{ backend.verbose_name }}
</a>
{% endif %}
{% if backend.identifier == "native" %}
{% if can_reset %}
<a href="{% url "control:auth.forgot" %}" class="btn btn-link btn-block">

View File

@@ -5,7 +5,12 @@
<dd>{{ payment_info.pos_id }}</dd>
<dt>{% trans "Receipt ID" %}</dt>
<dd>{{ payment_info.receipt_id }}</dd>
{% if payment_info.payment_type == "sumup" %}
{% if payment_info.payment_type == "stripe_terminal" %}
<dt>{% trans "Payment provider" %}</dt>
<dd>Stripe Terminal</dd>
<dt>{% trans "ID" %}</dt>
<dd>{{ payment_info.payment_data.payment_intent }}</dd>
{% elif payment_info.payment_type == "sumup" %}
<dt>{% trans "Payment provider" %}</dt>
<dd>SumUp</dd>
<dt>{% trans "Transaction Code" %}</dt>

View File

@@ -24,12 +24,6 @@
{% endblocktrans %}
</p>
{% bootstrap_field form.slug layout="inline" %}
<p>
{% blocktrans trimmed with slug=request.event.slug %}
Also, to make sure it's really you, please enter your user password here:
{% endblocktrans %}
</p>
{% bootstrap_field form.user_pw layout="inline" %}
<div class="form-group submit-group">
<button type="submit" class="btn btn-danger btn-save">

View File

@@ -14,6 +14,8 @@
{% bootstrap_field form.invoice_email_attachment layout="control" %}
{% bootstrap_field form.invoice_language layout="control" %}
{% bootstrap_field form.invoice_include_free layout="control" %}
{% bootstrap_field form.invoice_show_payments layout="control" %}
{% bootstrap_field form.invoice_reissue_after_modify layout="control" %}
{% bootstrap_field form.invoice_numbers_consecutive layout="control" %}
{% bootstrap_field form.invoice_numbers_prefix layout="control" %}
{% bootstrap_field form.invoice_numbers_prefix_cancellations layout="control" %}
@@ -42,6 +44,7 @@
<legend>{% trans "Invoice customization" %}</legend>
{% bootstrap_field form.invoice_renderer layout="control" %}
{% bootstrap_field form.invoice_attendee_name layout="control" %}
{% bootstrap_field form.invoice_include_expire_date layout="control" %}
{% bootstrap_field form.invoice_introductory_text layout="control" %}
{% bootstrap_field form.invoice_additional_text layout="control" %}
{% bootstrap_field form.invoice_footer_text layout="control" %}

View File

@@ -10,62 +10,75 @@
{% trans "Your changes have been saved." %}
</div>
{% endif %}
<div class="table-responsive">
<table class="table">
{% for plugin in plugins %}
<tr class="{% if plugin.app.compatibility_errors %}warning{% elif plugin.module in plugins_active %}success{% else %}default{% endif %}">
<td>
<strong>{{ plugin.name }}</strong>
{% if plugin.author %}
<p class="meta text-muted">{% blocktrans trimmed with v=plugin.version a=plugin.author %}
Version {{ v }} by <em>{{ a }}</em>
{% endblocktrans %}</p>
{% else %}
<p class="meta text-muted">{% blocktrans trimmed with v=plugin.version a=plugin.author %}
Version {{ v }}
{% endblocktrans %}</p>
{% endif %}
<p>{{ plugin.description }}</p>
{% if plugin.restricted and not request.user.is_staff %}
<span class="text-muted">
{% trans "This plugin needs to be enabled by a system administrator for your event." %}
</span>
{% endif %}
{% if plugin.app.compatibility_errors %}
<div class="alert alert-warning">
{% trans "This plugin cannot be enabled for the following reasons:" %}
<ul>
{% for e in plugin.app.compatibility_errors %}
<li>{{ e }}</li>
{% endfor %}
</ul>
</div>
{% endif %}
{% if plugin.app.compatibility_warnings %}
<div class="alert alert-warning">
{% trans "This plugin reports the following problems:" %}
<ul>
{% for e in plugin.app.compatibility_warnings %}
<li>{{ e }}</li>
{% endfor %}
</ul>
</div>
{% endif %}
</td>
<td class="text-right flip">
{% if plugin.app.compatibility_errors %}
<button class="btn disabled btn-block btn-default" disabled="disabled">{% trans "Incompatible" %}</button>
{% elif plugin.restricted and not staff_session %}
<button class="btn disabled btn-block btn-default" disabled="disabled">{% trans "Not available" %}</button>
{% elif plugin.module in plugins_active %}
<button class="btn btn-default btn-block" name="plugin:{{ plugin.module }}" value="disable">{% trans "Disable" %}</button>
{% else %}
<button class="btn btn-default btn-block" name="plugin:{{ plugin.module }}" value="enable">{% trans "Enable" %}</button>
{% endif %}
</td>
</tr>
{% endfor %}
</table>
<div class="tabbed-form">
{% for cat, catlabel, plist in plugins %}
<fieldset>
<legend>{{ catlabel }}</legend>
<div class="table-responsive">
<table class="table">
{% for plugin in plist %}
<tr class="{% if plugin.app.compatibility_errors %}warning{% elif plugin.module in plugins_active %}success{% else %}default{% endif %}">
<td>
<strong>{{ plugin.name }}</strong>
{% if plugin.author %}
<p class="meta text-muted">
{% blocktrans trimmed with v=plugin.version a=plugin.author %}
Version {{ v }} by <em>{{ a }}</em>
{% endblocktrans %}</p>
{% else %}
<p class="meta text-muted">
{% blocktrans trimmed with v=plugin.version a=plugin.author %}
Version {{ v }}
{% endblocktrans %}</p>
{% endif %}
<p>{{ plugin.description }}</p>
{% if plugin.restricted and not request.user.is_staff %}
<span class="text-muted">
{% trans "This plugin needs to be enabled by a system administrator for your event." %}
</span>
{% endif %}
{% if plugin.app.compatibility_errors %}
<div class="alert alert-warning">
{% trans "This plugin cannot be enabled for the following reasons:" %}
<ul>
{% for e in plugin.app.compatibility_errors %}
<li>{{ e }}</li>
{% endfor %}
</ul>
</div>
{% endif %}
{% if plugin.app.compatibility_warnings %}
<div class="alert alert-warning">
{% trans "This plugin reports the following problems:" %}
<ul>
{% for e in plugin.app.compatibility_warnings %}
<li>{{ e }}</li>
{% endfor %}
</ul>
</div>
{% endif %}
</td>
<td class="text-right flip" width="20%">
{% if plugin.app.compatibility_errors %}
<button class="btn disabled btn-block btn-default"
disabled="disabled">{% trans "Incompatible" %}</button>
{% elif plugin.restricted and not staff_session %}
<button class="btn disabled btn-block btn-default"
disabled="disabled">{% trans "Not available" %}</button>
{% elif plugin.module in plugins_active %}
<button class="btn btn-default btn-block" name="plugin:{{ plugin.module }}"
value="disable">{% trans "Disable" %}</button>
{% else %}
<button class="btn btn-default btn-block" name="plugin:{{ plugin.module }}"
value="enable">{% trans "Enable" %}</button>
{% endif %}
</td>
</tr>
{% endfor %}
</table>
</div>
</fieldset>
{% endfor %}
</div>
</form>
{% endblock %}

View File

@@ -1,2 +1,2 @@
{% load i18n %}{% if widget.wrap_label %}<label{% if widget.attrs.id %} for="{{ widget.attrs.id }}"{% endif %} class="preload-font"
data-family="{{ widget.label }}" data-style="regular">{% endif %}{% include "django/forms/widgets/input.html" %}{% if widget.wrap_label %} <strong>{{ widget.label }}</strong><br>{% trans "The quick brown fox jumps over the lazy dog." context "typography" %}</label>{% endif %}
{% load getitem %}{% load i18n %}{% if widget.wrap_label %}<label{% if widget.attrs.id %} for="{{ widget.attrs.id }}"{% endif %} class="preload-font"
data-family="{{ widget.label.title }}" data-style="regular">{% endif %}{% include "django/forms/widgets/input.html" %}{% if widget.wrap_label %} <strong>{{ widget.label.title }}</strong><br>{% trans "The quick brown fox jumps over the lazy dog." context "typography" %}{% if "sample" in widget.label.data %}<br>{{ widget.label.data.sample }}{% endif %}</label>{% endif %}

View File

@@ -73,13 +73,22 @@
</h3>
</div>
<div class="panel-body">
<div class="form-order-change" data-pricecalc-endpoint="{% url "api-v1:orderposition-price_calc" organizer=order.event.organizer.slug event=order.event.slug pk=position.pk %}" {% if position.subevent %}data-subevent="{{ position.subevent.id }}{% endif %}">
<div class="form-order-change" data-pricecalc-endpoint="{% url "api-v1:orderposition-price_calc" organizer=order.event.organizer.slug event=order.event.slug pk=position.pk %}" {% if position.subevent %}data-subevent="{{ position.subevent.id }}"{% endif %} data-position="{{ position.pk }}">
{% bootstrap_form_errors position.form %}
{% if position.custom_error %}
<div class="alert alert-danger">
{{ position.custom_error }}
</div>
{% endif %}
{% if position.voucher and position.voucher.budget %}
<div class="alert alert-warning">
{% blocktrans trimmed %}
This position has been created with a voucher with a limited budget. If you
change the price or item, the discount will still be calculated from the original
price at the time of purchase.
{% endblocktrans %}
</div>
{% endif %}
<div class="row">
<div class="col-sm-5 col-sm-offset-3">
<strong>{% trans "Current value" %}</strong>
@@ -181,7 +190,7 @@
{% bootstrap_formset_errors add_formset %}
<div data-formset-body>
{% for add_form in add_formset %}
<div class="panel panel-default items" data-formset-form>
<div class="panel panel-default items" data-formset-form data-subevent="0">
<div class="panel-heading">
<h3 class="panel-title">
<button type="button" class="btn btn-danger btn-xs pull-right flip"
@@ -219,7 +228,7 @@
</div>
<script type="form-template" data-formset-empty-form>
{% escapescript %}
<div class="panel panel-default items" data-formset-form>
<div class="panel panel-default items" data-formset-form data-subevent="0">
<div class="panel-heading">
<h3 class="panel-title">
<button type="button" class="btn btn-danger btn-xs pull-right flip"

View File

@@ -272,7 +272,9 @@
{% endif %}
{% if line.voucher %}
<br/><span class="fa fa-tags"></span> {% trans "Voucher code used:" %}
<a href="{% url "control:event.voucher" event=request.event.slug organizer=request.event.organizer.slug voucher=line.voucher.pk %}">
<a
{% if line.price_before_voucher|default_if_none:"NONE" != "NONE" %}data-toggle="tooltip" title="{% blocktrans trimmed with price=line.price_before_voucher|money:request.event.currency %}Original price: {{ price }}{% endblocktrans %}"{% endif %}
href="{% url "control:event.voucher" event=request.event.slug organizer=request.event.organizer.slug voucher=line.voucher.pk %}">
{{ line.voucher.code }}
</a>
{% endif %}

View File

@@ -0,0 +1,61 @@
{% extends "pretixcontrol/event/base.html" %}
{% load i18n %}
{% load static %}
{% load getitem %}
{% load bootstrap3 %}
{% block title %}{% trans "Import attendees" %}{% endblock %}
{% block content %}
<h1>{% trans "Import attendees" %}</h1>
<form action="" method="post" class="form-horizontal" data-asynctask data-asynctask-long>
{% csrf_token %}
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">{% trans "Data preview" %}</h3>
</div>
<div class="table-responsive panel-body">
<table class="table table-condensed">
<thead>
<tr>
{% for fn in parsed.fieldnames %}
<th>{{ fn }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for r in sample_rows %}
<tr>
{% for fn in parsed.fieldnames %}
<td>{{ r|getitem:fn }}</td>
{% endfor %}
</tr>
{% endfor %}
<tr>
<td class="text-center" colspan="{{ parsed.fieldnames|length }}">
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">{% trans "Import settings" %}</h3>
</div>
<div class="panel-body">
{% bootstrap_form_errors form %}
{% bootstrap_form form layout="horizontal" %}
<div class="alert alert-warning">
{% blocktrans trimmed %}
The import will be performed regardless of your quotas, so it will be possible to overbook your event using this option.
{% endblocktrans %}
</div>
</div>
</div>
<div class="form-group submit-group">
<button type="submit" class="btn btn-primary btn-save">
{% trans "Perform import" %}
</button>
</div>
</form>
{% endblock %}

View File

@@ -0,0 +1,31 @@
{% extends "pretixcontrol/event/base.html" %}
{% load i18n %}
{% load static %}
{% block title %}{% trans "Import attendees" %}{% endblock %}
{% block content %}
<h1>{% trans "Import attendees" %}</h1>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">{% trans "Upload a new file" %}</h3>
</div>
<div class="panel-body">
<form action="" method="post" enctype="multipart/form-data" class="form-inline">
{% csrf_token %}
<p>
{% blocktrans trimmed %}
The uploaded file should be a CSV file with a header row. You will be able to assign the
meanings of the different columns in the next step.
{% endblocktrans %}
</p>
<div class="form-group">
<label for="file">{% trans "Import file" %}: </label> <input id="file" type="file" name="file"/>
</div>
<div class="clearfix"></div>
<button class="btn btn-primary pull-right flip" type="submit">
<span class="icon icon-upload"></span> {% trans "Start import" %}
</button>
</form>
</div>
</div>
{% endblock %}

View File

@@ -32,6 +32,7 @@
{% endif %}
{% bootstrap_field sform.organizer_info_text layout="control" %}
{% bootstrap_field sform.event_team_provisioning layout="control" %}
{% bootstrap_field sform.giftcard_length layout="control" %}
</fieldset>
<fieldset>
<legend>{% trans "Organizer page" %}</legend>

View File

@@ -11,81 +11,95 @@
<span class="label label-warning">{% trans "TEST MODE" %}</span>
{% endif %}
</h1>
<div class="panel panel-primary items">
<div class="panel-heading">
<h3 class="panel-title">
{% trans "Details" %}
</h3>
</div>
<div class="panel-body">
<dl class="dl-horizontal">
<dt>{% trans "Gift card code" %}</dt>
<dd>{{ card.secret }}</dd>
<dt>{% trans "Creation date" %}</dt>
<dd>{{ card.issuance|date:"SHORT_DATETIME_FORMAT" }}</dd>
<dt>{% trans "Current value" %}</dt>
<dd>{{ card.value|money:card.currency }}</dd>
<dt>{% trans "Currency" %}</dt>
<dd>{{ card.currency }}</dd>
{% if card.issued_in %}
<dt>{% trans "Issued through sale" %}</dt>
<dd>
<a href="{% url "control:event.order" event=card.issued_in.order.event.slug organizer=card.issued_in.order.event.organizer.slug code=card.issued_in.order.code %}">
{{ card.issued_in.order.full_code }}</a>-{{ card.issued_in.positionid }}
</dd>
{% endif %}
</dl>
</div>
</div>
<div class="panel panel-default items">
<div class="panel-heading">
<h3 class="panel-title">
{% trans "Transactions" %}
</h3>
</div>
<table class="panel-body table">
<thead>
<tr>
<th>{% trans "Date" %}</th>
<th>{% trans "Order" %}</th>
<th class="text-right">{% trans "Value" %}</th>
</tr>
</thead>
<tbody>
{% for t in card.transactions.all %}
<tr>
<td>{{ t.datetime|date:"SHORT_DATETIME_FORMAT" }}</td>
<td>
{% if t.order %}
<a href="{% url "control:event.order" event=t.order.event.slug organizer=t.order.event.organizer.slug code=t.order.code %}">
{{ t.order.full_code }}
</a>
{% else %}
<em>{% trans "Manual transaction" %}</em>
<div class="row">
<div class="col-md-10 col-xs-12">
<div class="panel panel-primary items">
<div class="panel-heading">
<h3 class="panel-title">
{% trans "Details" %}
</h3>
</div>
<div class="panel-body">
<dl class="dl-horizontal">
<dt>{% trans "Gift card code" %}</dt>
<dd>{{ card.secret }}</dd>
<dt>{% trans "Creation date" %}</dt>
<dd>{{ card.issuance|date:"SHORT_DATETIME_FORMAT" }}</dd>
<dt>{% trans "Current value" %}</dt>
<dd>{{ card.value|money:card.currency }}</dd>
<dt>{% trans "Currency" %}</dt>
<dd>{{ card.currency }}</dd>
{% if card.issued_in %}
<dt>{% trans "Issued through sale" %}</dt>
<dd>
<a href="{% url "control:event.order" event=card.issued_in.order.event.slug organizer=card.issued_in.order.event.organizer.slug code=card.issued_in.order.code %}">
{{ card.issued_in.order.full_code }}</a>-{{ card.issued_in.positionid }}
</dd>
{% endif %}
</td>
<td class="text-right">
{{ t.value|money:card.currency }}
</td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr>
<td></td>
<td></td>
<td class="text-right">
<form class="helper-display-inline form-inline" method="post" action="">
{% csrf_token %}
<input type="text" class="form-control input-sm" placeholder="{% trans "Value" %}" name="value">
<button class="btn btn-primary">
<span class="fa fa-plus"></span>
</button>
</form>
</td>
</dl>
</div>
</div>
<div class="panel panel-default items">
<div class="panel-heading">
<h3 class="panel-title">
{% trans "Transactions" %}
</h3>
</div>
<table class="panel-body table">
<thead>
<tr>
<th>{% trans "Date" %}</th>
<th>{% trans "Order" %}</th>
<th class="text-right">{% trans "Value" %}</th>
</tr>
</thead>
<tbody>
{% for t in card.transactions.all %}
<tr>
<td>{{ t.datetime|date:"SHORT_DATETIME_FORMAT" }}</td>
<td>
{% if t.order %}
<a href="{% url "control:event.order" event=t.order.event.slug organizer=t.order.event.organizer.slug code=t.order.code %}">
{{ t.order.full_code }}
</a>
{% else %}
<em>{% trans "Manual transaction" %}</em>
{% endif %}
</td>
<td class="text-right">
{{ t.value|money:card.currency }}
</td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr>
<td></td>
<td></td>
<td class="text-right">
<form class="helper-display-inline form-inline" method="post" action="">
{% csrf_token %}
<input type="text" class="form-control input-sm" placeholder="{% trans "Value" %}" name="value">
<button class="btn btn-primary">
<span class="fa fa-plus"></span>
</button>
</form>
</td>
</tr>
</tfoot>
</table>
</tr>
</tfoot>
</table>
</div>
</div>
<div class="col-md-2 col-xs-12">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
{% trans "Gift card history" %}
</h3>
</div>
{% include "pretixcontrol/includes/logs.html" with obj=card %}
</div>
</div>
</div>
{% endblock %}

View File

@@ -198,11 +198,24 @@
</div>
<div class="col-sm-12 help-inline">
<p>
After you changed the page size, you need to create a new empty background. If you
want to use a custom background, it already needs to have the correct size.
{% blocktrans trimmed %}
After you changed the page size, you need to create a new empty background. If you
want to use a custom background, it already needs to have the correct size.
{% endblocktrans %}
</p>
</div>
</div>
<div class="row control-group pdf-info">
<div class="col-sm-12">
<label>{% trans "Prefered language" %}</label><br>
<select class="form-control" id="pdf-info-locale">
<option value="">{% trans "Order locale" %}</option>
{% for l in locales %}
<option value="{{ l.0 }}">{{ l.1 }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="row control-group position">
<div class="col-sm-6">
<label>{% trans "x (mm)" %}</label><br>
@@ -251,6 +264,12 @@
<span class="fa fa-italic"></span>
</button>
</div>
<div class="btn-group" role="group">
<button type="button" class="btn btn-default toggling" data-action="downward"
data-toggle="tooltip" title="{% trans "Flow multiple lines downward from specified position" %}">
<span class="fa fa-caret-square-o-down"></span>
</button>
</div>
</div>
</div>
</div>
@@ -293,11 +312,16 @@
</div>
</div>
<div class="row control-group text">
<div class="col-sm-12">
<div class="col-sm-6">
<label>{% trans "Width (mm)" %}</label><br>
<input type="number" value="13" class="input-block-level form-control" step="0.01"
id="toolbox-textwidth">
</div>
<div class="col-sm-6">
<label>{% trans "Rotation (°)" %}</label><br>
<input type="number" value="0" class="input-block-level form-control" step="0.1"
id="toolbox-textrotation">
</div>
</div>
<div class="row control-group poweredby">
<div class="col-sm-12">
@@ -379,9 +403,12 @@
<img src="{% static 'pretixpresale/pdf/powered_by_pretix_white.png' %}" id="poweredby-white" class="sr-only">
{% for family, styles in fonts.items %}
{% for style, formats in styles.items %}
{% if "sample" not in style %}
<span class="preload-font" data-family="{{ family }}" data-style="{{ style }}">
giItT1WQy@!-/#
{% if "sample" in styles %}{{ styles.sample }}{% endif %}
</span>
{% endif %}
{% endfor %}
{% endfor %}
{% endblock %}

View File

@@ -1,7 +1,20 @@
{% load static %}
@font-face {
font-family: 'AND';
font-style: normal;
font-weight: normal;
src: url('{% static "fonts/AND-Regular.ttf" %}') format('truetype');
}
@font-face {
font-family: 'AND';
font-style: normal;
font-weight: bold;
src: url('{% static "fonts/AND-Regular.ttf" %}') format('truetype');
}
{% for family, styles in fonts.items %}
{% for style, formats in styles.items %}
{% if "sample" not in style %}
@font-face {
font-family: '{{ family }}';
{% if style == "italic" or style == "bolditalic" %}
@@ -19,7 +32,7 @@
{% if "truetype" in formats %}url('{% static formats.truetype %}') format('truetype'){% endif %};
}
.preload-font[data-family="{{family}}"][data-style="{{style}}"] {
font-family: '{{ family }}';
font-family: '{{ family }}', 'AND';
{% if style == "italic" or style == "bolditalic" %}
font-style: italic;
{% else %}
@@ -32,5 +45,6 @@
{% endif %}
}
{% endif %}
{% endfor %}
{% endfor %}

View File

@@ -40,12 +40,12 @@
<fieldset>
<legend>{% trans "Step 3: Confirm deletion" %}</legend>
<p>
{% blocktrans trimmed with event=request.event.name %}
{% blocktrans trimmed with event=request.event.name slug=request.event.slug %}
Please re-check that you are fully certain that you want to delete the selected categories of data from the event <strong>{{ event }}</strong>.
In this case, please enter your user password here:
To confirm you really want this, please type out the event's short name ("{{ slug }}") here:
{% endblocktrans %}
</p>
<input type="password" class="form-control" name="password" required placeholder="{% trans "Your password" %}">
<input type="text" class="form-control" name="slug" required placeholder="{% trans "Event short name" %}">
</fieldset>
<input type="hidden" name="file" value="{{ file.pk }}">
<div class="form-group submit-group">

View File

@@ -8,7 +8,11 @@
{% csrf_token %}
<h3>{% trans "Welcome back!" %}</h3>
<p>
{% trans "We just want to make sure it's really you. Please re-enter your password to continue." %}
{% if form.backend.url %}
{% blocktrans trimmed with login_provider=form.backend.verbose_name %}We just want to make sure it's really you. Please re-authenticate with '{{ login_provider }}'.{% endblocktrans %}
{% else %}
{% trans "We just want to make sure it's really you. Please re-enter your password to continue." %}
{% endif %}
</p>
{% bootstrap_form form %}
<input class="form-control" id="webauthn-response" name="webauthn"
@@ -23,9 +27,15 @@
</small></p>
{% endif %}
<div class="form-group text-right flip">
<button type="submit" class="btn btn-primary btn-block">
{% trans "Continue" %}
</button>
{% if form.backend.url %}
<a href="{{ form.backend.url }}" class="btn btn-primary btn-block">
{% trans "Continue" %}
</a>
{% else %}
<button type="submit" class="btn btn-primary btn-block">
{% trans "Continue" %}
</button>
{% endif %}
<a href="{% url "control:auth.logout" %}" class="btn btn-link btn-block">
{% trans "Log in as someone else" %}
</a>

Some files were not shown because too many files have changed in this diff Show More