Compare commits

..

9 Commits

Author SHA1 Message Date
Raphael Michel
dc0b73bf19 Fix issues introduced in rebase 2016-11-27 17:13:26 +01:00
Raphael Michel
ed31f31c04 Added a test for the cart methods 2016-11-27 16:13:58 +01:00
Raphael Michel
b1e78b5b78 Fix failing tests 2016-11-27 16:13:58 +01:00
Raphael Michel
4e2d31154a Fix dummy lock function 2016-11-27 16:13:58 +01:00
Raphael Michel
2e5a598b5f Restructure checkout to reduce locking times 2016-11-27 16:13:58 +01:00
Raphael Michel
4b535b067a Move two calls out of the lock period in OrderChangeManager 2016-11-27 16:13:58 +01:00
Raphael Michel
4f6eb903c7 mark_order_paid: Only lock when necessary 2016-11-27 16:13:58 +01:00
Raphael Michel
4d916df7c0 Restructure add_to_cart 2016-11-27 16:13:57 +01:00
Raphael Michel
61a331493e Reduce locked timeframe in add_items_to_cart 2016-11-27 16:12:38 +01:00
827 changed files with 8870 additions and 123414 deletions

View File

@@ -1,35 +0,0 @@
codecov:
notify:
require_ci_to_pass: yes
coverage:
precision: 2
round: down
range: "60...100"
status:
project:
default:
target: auto
threshold: 2%
base: auto
patch:
default:
target: auto
threshold: 2%
base: auto
changes: no
parsers:
gcov:
branch_detection:
conditional: yes
loop: yes
method: no
macro: no
comment:
require_changes: yes
layout: "header, diff, files"
behavior: default
require_changes: no

14
.gitattributes vendored
View File

@@ -3,18 +3,4 @@ src/static/lightbox/* linguist-vendored
src/static/typeahead/* linguist-vendored
src/static/moment/* linguist-vendored
src/static/datetimepicker/* linguist-vendored
src/static/colorpicker/* linguist-vendored
src/static/fileupload/* linguist-vendored
src/static/charts/* linguist-vendored
src/pretix/plugins/ticketoutputpdf/static/pretixplugins/ticketoutputpdf/fabric.* linguist-vendored
src/pretix/plugins/ticketoutputpdf/static/pretixplugins/ticketoutputpdf/pdf.* linguist-vendored
# Denote all files that are truly binary and should not be modified.
*.eot binary
*.otf binary
*.ttf binary
*.woff binary
*.zip binary
*.png binary
*.gif binary
*.jpg binary

2
.gitignore vendored
View File

@@ -21,6 +21,4 @@ pretixeu/
local/
.project
.pydevproject
.DS_Store

View File

@@ -2,32 +2,11 @@ before_script:
tests:
stage: test
script:
- virtualenv env
- virtualenv-3.4 env
- source env/bin/activate
- pip install -U pip wheel setuptools
- XDG_CACHE_HOME=/cache bash .travis.sh style
- XDG_CACHE_HOME=/cache bash .travis.sh tests
- XDG_CACHE_HOME=/cache bash .travis.sh doctests
tags:
- python3
pypi:
stage: release
script:
- cp /keys/.pypirc ~/.pypirc
- virtualenv env
- source env/bin/activate
- pip install -U pip wheel setuptools
- XDG_CACHE_HOME=/cache pip3 install -Ur src/requirements.txt -r src/requirements/dev.txt -r src/requirements/py34.txt
- cd src
- python setup.py sdist upload
- python setup.py bdist_wheel upload
tags:
- python3
only:
- release
artifacts:
paths:
- src/dist/
stages:
- test
- build
- release

View File

@@ -4,16 +4,6 @@ set -x
echo "Executing job $1"
if [ "$PRETIX_CONFIG_FILE" == "tests/travis_mysql.cfg" ]; then
mysql -u root -e 'CREATE DATABASE pretix DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;'
pip3 install -Ur src/requirements/mysql.txt
fi
if [ "$PRETIX_CONFIG_FILE" == "tests/travis_postgres.cfg" ]; then
psql -c 'create database travis_ci_test;' -U postgres
pip3 install -Ur src/requirements/postgres.txt
fi
if [ "$1" == "style" ]; then
XDG_CACHE_HOME=/cache pip3 install -Ur src/requirements.txt -r src/requirements/dev.txt -r src/requirements/py34.txt
cd src
@@ -30,27 +20,12 @@ if [ "$1" == "tests" ]; then
cd src
python manage.py check
make all compress
py.test --rerun 5 tests
coverage run -m py.test --rerun 5 tests && coverage report
fi
if [ "$1" == "tests-cov" ]; then
pip3 install -r src/requirements.txt -Ur src/requirements/dev.txt -r src/requirements/py34.txt
cd src
python manage.py check
make all compress
coverage run -m py.test --rerun 5 tests && codecov
fi
if [ "$1" == "plugins" ]; then
pip3 install -r src/requirements.txt -Ur src/requirements/dev.txt -r src/requirements/py34.txt
cd src
python setup.py develop
make all compress
pushd ~
git clone --depth 1 https://github.com/pretix/pretix-cartshare.git
cd pretix-cartshare
python setup.py develop
make
py.test --rerun 5 tests
popd
coverage run -m py.test --rerun 5 tests && coveralls
fi

View File

@@ -1,40 +1,15 @@
language: python
sudo: false
python:
- "3.4"
install:
- pip install -U pip wheel setuptools==28.6.1
- pip install -U pip wheel setuptools==28.6.1
script:
- bash .travis.sh $JOB
- bash .travis.sh $JOB
cache:
directories:
- $HOME/.cache/pip
services:
- mysql
- postgresql
matrix:
include:
- python: 3.4
env: JOB=tests PRETIX_CONFIG_FILE=tests/sqlite.cfg
- python: 3.5
env: JOB=tests PRETIX_CONFIG_FILE=tests/sqlite.cfg
- python: 3.6
env: JOB=tests PRETIX_CONFIG_FILE=tests/sqlite.cfg
- python: 3.4
env: JOB=tests PRETIX_CONFIG_FILE=tests/travis_mysql.cfg
- python: 3.5
env: JOB=tests PRETIX_CONFIG_FILE=tests/travis_mysql.cfg
- python: 3.6
env: JOB=tests PRETIX_CONFIG_FILE=tests/travis_mysql.cfg
- python: 3.4
env: JOB=tests PRETIX_CONFIG_FILE=tests/travis_postgres.cfg
- python: 3.5
env: JOB=tests PRETIX_CONFIG_FILE=tests/travis_postgres.cfg
- python: 3.6
env: JOB=tests PRETIX_CONFIG_FILE=tests/travis_postgres.cfg
- python: 3.4
env: JOB=style
- python: 3.4
env: JOB=plugins
- python: 3.4
env: JOB=tests-cov
addons:
postgresql: "9.4"
directories:
- $HOME/.cache/pip
env:
- JOB=style
- JOB=doctests
- JOB=tests-cov

18
AUTHORS
View File

@@ -3,35 +3,21 @@ people who have submitted patches, reported bugs, added translations, helped
answer newbie questions, improved the documentation, and generally made pretix
an awesome project. Thank you all!
Adam K. Sumner <asumner101@gmail.com>
Ahrdie <robert.deppe@me.com>
Alexander Brock <Brock.Alexander@web.de>
Brandon Pineda
Bolutife Lawrence
Ben Oswald
Christian Franke <nobody@nowhere.ws>
Christopher Dambamuromo <me@chridam.com>
chotee <chotee@openended.eu>
Cpt. Foo
Daniel Rosenblüh
Enrique Saez
Flavia Bastos
informancer <informancer@web.de>
Jakob Schnell <github@ezelo.de>
Jan Felix Wiebe <git@jfwie.be>
Jan Weiß
Jason Estibeiro <jasonestibeiro@live.com>
jlwt90
Jan Weiß
Jonas Große Sundrup <cherti@letopolis.de>
Kevin Nelson
Leah Oswald
Lukas Martini
Nathan Mattes
Nicole Klünder
Marc-Pascal Clement
Martin Gross <martin@pc-coholic.de>
Raphael Michel <mail@raphaelmichel.de>
Team MRMCD
Tobias Kunze <rixx@cutebit.de>
Oliver Knapp <github@oliverknapp.de>
Vishal Sodani <vishalsodani@rediffmail.com>
Jan Felix Wiebe <git@jfwie.be>

View File

@@ -1,46 +1,49 @@
FROM debian:jessie
RUN apt-get update && \
apt-get install -y python3 git python3-pip \
libxml2-dev libxslt1-dev python-dev python-virtualenv locales libffi-dev \
build-essential python3-dev zlib1g-dev libssl-dev gettext \
libpq-dev libmysqlclient-dev libmemcached-dev libjpeg-dev \
aqbanking-tools supervisor nginx sudo \
--no-install-recommends && \
apt-get clean && \
rm -rf /var/lib/apt/lists/* && \
dpkg-reconfigure locales && \
locale-gen C.UTF-8 && \
/usr/sbin/update-locale LANG=C.UTF-8 && \
mkdir /etc/pretix && \
mkdir /data && \
useradd -ms /bin/bash -d /pretix -u 15371 pretixuser && \
echo 'pretixuser ALL=(ALL) NOPASSWD: /usr/bin/supervisord' >> /etc/sudoers && \
mkdir /static
RUN apt-get update && apt-get install -y python3 git python3-pip \
libxml2-dev libxslt1-dev python-dev python-virtualenv locales libffi-dev \
build-essential python3-dev zlib1g-dev libssl-dev gettext \
libpq-dev libmysqlclient-dev libmemcached-dev libjpeg-dev \
aqbanking-tools supervisor nginx sudo \
--no-install-recommends
ENV LC_ALL=C.UTF-8 \
DJANGO_SETTINGS_MODULE=production_settings
WORKDIR /
RUN dpkg-reconfigure locales && \
locale-gen C.UTF-8 && \
/usr/sbin/update-locale LANG=C.UTF-8
ENV LC_ALL C.UTF-8
RUN apt-get clean && rm -rf /var/lib/apt/lists/*
RUN useradd -ms /bin/bash -d /pretix -u 15371 pretixuser
RUN echo 'pretixuser ALL=(ALL) NOPASSWD: /usr/bin/supervisord' >> /etc/sudoers
RUN mkdir /etc/pretix
RUN mkdir /data
VOLUME /etc/pretix
COPY deployment/docker/pretix.bash /usr/local/bin/pretix
RUN chmod +x /usr/local/bin/pretix
COPY deployment/docker/supervisord.conf /etc/supervisord.conf
COPY deployment/docker/nginx.conf /etc/nginx/nginx.conf
COPY deployment/docker/production_settings.py /pretix/src/production_settings.py
RUN rm /etc/nginx/sites-enabled/default
COPY src /pretix/src
WORKDIR /pretix/src
ADD deployment/docker/production_settings.py /pretix/src/production_settings.py
ENV DJANGO_SETTINGS_MODULE production_settings
RUN chmod +x /usr/local/bin/pretix && \
rm /etc/nginx/sites-enabled/default && \
pip3 install -U pip wheel setuptools && \
cd /pretix/src && \
rm -f pretix.cfg && \
pip3 install -r requirements.txt -r requirements/mysql.txt -r requirements/postgres.txt \
-r requirements/memcached.txt -r requirements/redis.txt \
-r requirements/py34.txt gunicorn && \
mkdir -p data && \
chown -R pretixuser:pretixuser /pretix /data data && \
sudo -u pretixuser make production
RUN pip3 install -r requirements.txt -r requirements/mysql.txt -r requirements/postgres.txt \
-r requirements/memcached.txt -r requirements/redis.txt \
-r requirements/py34.txt gunicorn
RUN mkdir /static && chown -R pretixuser:pretixuser /static /pretix /data
USER pretixuser
VOLUME ["/etc/pretix", "/data"]
RUN make production
EXPOSE 80
ENTRYPOINT ["pretix"]
CMD ["all"]

41
README.md Normal file
View File

@@ -0,0 +1,41 @@
pretix
======
[![Docs](https://readthedocs.org/projects/pretix/badge/?version=latest)](http://docs.pretix.eu/en/latest/)
[![Build Status](https://travis-ci.org/pretix/pretix.svg?branch=master)](https://travis-ci.org/pretix/pretix)
[![Coverage Status](https://img.shields.io/coveralls/pretix/pretix.svg)](https://coveralls.io/r/pretix/pretix)
Reinventing ticket presales, one bit at a time.
Project status
--------------
Most features are present and sufficiently stable. pretix has been in use for multiple event and
sold a few thousand tickets so far. There is still a bunch of features to come and there surely is
still a bunch of bugs in there, but we consider it stable enough that we use it in production ourselves.
If you deploy and use pretix, there will be a safe upgrade path for all changes to come. We're planning
on an 1.0 release in late 2016 or early 2017. Until then, we take the liberty of changing the code as we
like, but we try to keep the changes to documented APIs as small as possible. If you want to use pretix
in production or develop a plugin now, I invite you to send me an email so that I can notify you of changes
and bugs that require your attention.
Since very recently we now have an [installation guide](https://docs.pretix.eu/en/latest/admin/installation/index.html)
in our documentation.
Contributing
------------
If you want to contribute to pretix, please read the [developer documentation](https://docs.pretix.eu/en/latest/development/index.html)
in our documentation. If you have any further questions, please do not hesitate to ask!
License
-------
The code in this repository is published under the terms of the Apache License.
See the LICENSE file for the complete license text.
This project is maintained by Raphael Michel <mail@raphaelmichel.de>. See the
AUTHORS file for a list of all the awesome folks who contributed to this project.
This project is 100 percent free and open source software. If you are interested in
commercial support, hosting services or supporting this project financially, please
go to [pretix.eu](https://pretix.eu) or contact Raphael directly.

View File

@@ -1,54 +0,0 @@
pretix
======
.. image:: https://img.shields.io/pypi/v/pretix.svg
:target: https://pypi.python.org/pypi/pretix
.. image:: https://readthedocs.org/projects/pretix/badge/?version=latest
:target: https://docs.pretix.eu/en/latest/
.. image:: https://travis-ci.org/pretix/pretix.svg?branch=master
:target: https://travis-ci.org/pretix/pretix
.. image:: https://codecov.io/gh/pretix/pretix/branch/master/graph/badge.svg
:target: https://codecov.io/gh/pretix/pretix
Reinventing ticket presales, one ticket at a time.
Project status & release cycle
------------------------------
While there is always a lot to do and improve on, pretix by now has been in use for more than a dozen
conferences that sold over ten thousand tickets combined without major problems. We therefore think of
pretix as being stable and ready to use.
If you want to use or extend pretix, we strongly recommend to follow our `blog`_. We will announce all
releases there. You can always find the latest stable version on PyPI or in the ``release/X.Y`` branch of
this repository. The ``master`` branch contains a development version that we also try to keep stable in
the sense that it does not break your data, but its APIs might change without prior notice.
To get started using pretix on your own server, look at the `installation guide`_ in our documentation.
This project is 100 percent free and open source software. If you are interested in commercial support,
hosting services or supporting this project financially, please go to `pretix.eu`_ or contact us at
support@pretix.eu.
Contributing
------------
If you want to contribute to pretix, please read the `developer documentation`_
in our documentation. If you have any further questions, please do not hesitate to ask!
License
-------
The code in this repository is published under the terms of the Apache License.
See the LICENSE file for the complete license text.
This project is maintained by Raphael Michel <mail@raphaelmichel.de>. See the
AUTHORS file for a list of all the awesome folks who contributed to this project.
.. _installation guide: https://docs.pretix.eu/en/latest/admin/installation/index.html
.. _developer documentation: https://docs.pretix.eu/en/latest/development/index.html
.. _pretix.eu: https://pretix.eu
.. _blog: https://pretix.eu/about/en/blog/

View File

@@ -22,11 +22,9 @@ http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
add_header X-Content-Type-Options nosniff;
access_log /var/log/nginx/access.log private;
error_log /var/log/nginx/error.log;
add_header Referrer-Policy same-origin;
gzip on;
gzip_disable "msie6";
@@ -50,16 +48,8 @@ http {
expires 7d;
access_log off;
}
location ^~ /media/cachedfiles {
deny all;
return 404;
}
location ^~ /media/invoices {
deny all;
return 404;
}
location /static/ {
alias /pretix/src/pretix/static.dist/;
alias /static/;
access_log off;
expires 365d;
add_header Cache-Control "public";

View File

@@ -33,7 +33,7 @@ fi
if [ "$1" == "taskworker" ]; then
export C_FORCE_ROOT=True
exec celery -A pretix.celery_app worker -l info
exec celery -A pretix worker -l info
fi
if [ "$1" == "shell" ]; then

View File

@@ -1,4 +1,6 @@
from pretix.settings import *
LOGGING['handlers']['mail_admins']['include_html'] = True
STATIC_ROOT = '/static'
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'

View File

@@ -16,9 +16,7 @@ the files found before.
The file is expected to be in the INI format as specified in the `Python documentation`_.
The config file may contain the following sections (all settings are optional and have
default values). We suggest that you start from the examples given in one of the
installation tutorials.
The config file may contain the following sections (all settings are optional and have default values).
pretix settings
---------------
@@ -102,10 +100,6 @@ Example::
``user``, ``password``, ``host``, ``port``
Connection details for the database connection. Empty by default.
``galera``
Indicates if the database backend is a MySQL/MariaDB Galera cluster and
turns on some optimizations/special case handlers. Default: ``False``
URLs
----
@@ -155,8 +149,6 @@ Example::
``admins``
Comma-separated list of email addresses that should receive a report about every error code 500 thrown by pretix.
.. _`django-settings`:
Django settings
---------------
@@ -181,11 +173,6 @@ Example::
.. WARNING:: Never set this to ``True`` in production!
``profile``
Enable code profiling for a random subset of requests. Disabled by default, see
:ref:`perf-monitoring` for details.
.. _`metrics-settings`:
Metrics
-------
@@ -214,9 +201,6 @@ You can use an existing memcached server as pretix's caching backend::
If no memcached is configured, pretix will use Django's built-in local-memory caching method.
.. note:: If you use memcached and you deploy pretix across multiple servers, you should use *one*
shared memcached instance, not multiple ones, because cache invalidations would not be
propagated otherwise.
Redis
-----
@@ -254,19 +238,6 @@ RabbitMQ might be the better choice if you have a complex, multi-server, high-pe
but as you already should have a redis instance ready for session and lock storage, we recommend
redis for convenience. See the `Celery documentation`_ for more details.
Sentry
------
pretix has native support for sentry, a tool that you can use to track errors in the
application. If you want to use sentry, you need to set a DSN in the configuration file::
[sentry]
dsn=https://<key>:<secret>@sentry.io/<project>
``dsn``
You will be given this value by your sentry installation.
Secret length
-------------

View File

@@ -10,4 +10,3 @@ Contents:
installation/index
config
maintainance

View File

@@ -74,7 +74,7 @@ redis instance to be running on the same host. To avoid the hassle with network
recommend connecting to redis via a unix socket. To enable redis on unix sockets, add the following to your
``/etc/redis/redis.conf``::
unixsocket /var/run/redis/redis.sock
unixsocket /tmp/redis.sock
unixsocketperm 777
Now restart redis-server::
@@ -111,7 +111,7 @@ Fill the configuration file ``/etc/pretix/pretix.cfg`` with the following conten
datadir=/data
[database]
; Replace mysql with postgresql_psycopg2 for PostgreSQL
; Replace mysql with psycopg2 for PostgreSQL
backend=mysql
name=pretix
user=pretix
@@ -127,23 +127,23 @@ Fill the configuration file ``/etc/pretix/pretix.cfg`` with the following conten
host=172.17.0.1
[redis]
location=unix:///var/run/redis/redis.sock?db=0
location=unix:///tmp/redis.sock?db=0
; Remove the following line if you are unsure about your redis' security
; to reduce impact if redis gets compromised.
sessions=true
[celery]
backend=redis+socket:///var/run/redis/redis.sock?virtual_host=1
broker=redis+socket:///var/run/redis/redis.sock?virtual_host=2
backend=redis+socket:///tmp/redis.sock?virtual_host=1
broker=redis+socket:///tmp/redis.sock?virtual_host=2
See :ref:`email configuration <mail-settings>` to learn more about configuring mail features.
Docker image and service
------------------------
First of all, download the latest stable pretix image by running::
First of all, download the latest pretix image by running::
$ docker pull pretix/standalone:stable
$ docker pull pretix/standalone:latest
We recommend starting the docker container using systemd to make sure it runs correctly after a reboot. Create a file
named ``/etc/systemd/system/pretix.service`` with the following content::
@@ -160,7 +160,7 @@ named ``/etc/systemd/system/pretix.service`` with the following content::
ExecStart=/usr/bin/docker run --name %n -p 8345:80 \
-v /var/pretix-data:/data \
-v /etc/pretix:/etc/pretix \
-v /var/run/redis:/var/run/redis \
-v /tmp/redis.sock:/tmp/redis.sock \
-v /var/run/mysqld:/var/run/mysqld \
pretix/standalone all
ExecStop=/usr/bin/docker stop %n
@@ -168,7 +168,7 @@ named ``/etc/systemd/system/pretix.service`` with the following content::
[Install]
WantedBy=multi-user.target
You can leave the MySQL socket volume out if you're using PostgreSQL. You can now run the following commands
You can leave the MySQL socket volume out if you're using PostgreSQL. You can now run the following comamnds
to enable and start the service::
# systemctl daemon-reload
@@ -222,8 +222,6 @@ Yay, you are done! You should now be able to reach pretix at https://pretix.your
*admin@localhost* with a password of *admin*. Don't forget to change that password! Create an organizer first, then
create an event and start selling tickets!
You should probably read :ref:`maintainance` next.
Updates
-------
@@ -231,33 +229,11 @@ Updates
Updates are fairly simple, but require at least a short downtime::
# docker pull pretix/standalone:stable
# docker pull pretix/standalone
# systemctl restart pretix.service
# docker exec -it pretix.service pretix upgrade
Restarting the service can take a few seconds, especially if the update requires changes to the database.
Replace ``stable`` above with a specific version number like ``1.0`` or with ``latest`` for the development
version, if you want to.
Install a plugin
----------------
To install a plugin, you need to build your own docker image. To do so, create a new directory and place a file
named ``Dockerfile`` in it. The Dockerfile could look like this (replace ``pretix-passbook`` with the plugins of your
choice)::
FROM pretix/standalone:stable
USER root
RUN pip3 install pretix-passbook
USER pretixuser
RUN cd /pretix/src && make production
Then, go to that directory and build the image::
$ docker build -t mypretix
You can now use that image ``mypretix`` instead of ``pretix/standalone`` in your service file (see above). Be sure
to re-build your custom image after you pulled ``pretix/standalone`` if you want to perform an update.
.. _Docker: https://docs.docker.com/engine/installation/linux/debian/
.. _Postfix: https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-postfix-as-a-send-only-smtp-server-on-ubuntu-16-04

View File

@@ -5,33 +5,51 @@ General remarks
Requirements
------------
To use pretix, you will need the following things:
To use pretix, the most minimal setup consists of:
* **pretix** and the python packages it depends on
* An **WSGI application server** (we recommend gunicorn)
* A periodic task runner, e.g. ``cron``
* **A database**. This needs to be a SQL-based that is supported by Django. We highly recommend to either
go for **PostgreSQL** or **MySQL/MariaDB**. If you do not provide one, pretix will run on SQLite, which is useful
for evaluation and development purposes.
To run pretix, you will need **at least Python 3.4**. We only recommend installations on **Linux**, Windows is not
officially supported (but might work).
.. warning:: Do not ever use SQLite in production. It will break.
Optional requirements
---------------------
* A **reverse proxy**. pretix needs to deliver some static content to your users (e.g. CSS, images, ...). While pretix
is capable of doing this, having this handled by a proper web server like **nginx** or **Apache** will be much
faster. Also, you need a proxying web server in front to provide SSL encryption.
pretix is built in a way that makes many of the following requirements optional. However, performance or security might
be very low if you skip some of them, therefore they are only partly optional.
.. warning:: Do not ever run without SSL in production. Your users deserve encrypted connections and thanks to
`Let's Encrypt`_ SSL certificates can be obtained for free these days.
Database
A good SQL-based database to run on that is supported by Django. We highly recommend to either go for **PostgreSQL**
or **MySQL/MariaDB**.
If you do not provide one, pretix will run on SQLite, which is useful for evaluation and development purposes.
* A **redis** server. This will be used for caching, session storage and task queuing.
.. warning:: Do not ever use SQLite in production. It will break.
.. warning:: pretix can run without redis, however this is only intended for development and should never be
used in production.
Reverse proxy
pretix needs to deliver some static content to your users (e.g. CSS, images, ...). While pretix is capable of
doing this, having this handled by a proper web server like **nginx** or **Apache** will be much faster. Also, you
need a proxying web server in front to provide SSL encryption.
* Optionally: RabbitMQ or memcached. Both of them might provide speedups, but if they are not present,
redis will take over their job.
.. warning:: Do not ever run without SSL in production. Your users deserve encrypted connections and thanks to
`Let's Encrypt`_ SSL certificates can be obtained for free these days.
Task worker
When pretix has to do heavy stuff, it is better to offload it into a background process instead of having the
users connection wait. Therefore pretix provides a background service that can be used to work on those
longer-running tasks.
This requires at least Redis (and optionally RabbitMQ).
Redis
If you provide a redis instance, pretix is able to make use of it in the three following ways:
* Caching
* Fast session storage
* Queuing and result storage for the task worker queue
RabbitMQ
RabbitMQ can be used as a more advanced queue manager for the task workers if necessary.
.. _Let's Encrypt: https://letsencrypt.org/

View File

@@ -38,10 +38,10 @@ Unix user
As we do not want to run pretix as root, we first create a new unprivileged user::
# adduser pretix --disabled-password --home /var/pretix
# sudo adduser pretix --disabled-password --home /var/pretix
In this guide, all code lines prepended with a ``#`` symbol are commands that you need to execute on your server as
``root`` user (e.g. using ``sudo``); all lines prepended with a ``$`` symbol should be run by the unprivileged user.
``root`` user; all lines prepended with a ``$`` symbol should be run by the unprivileged user.
Database
--------
@@ -82,7 +82,7 @@ Fill the configuration file ``/etc/pretix/pretix.cfg`` with the following conten
datadir=/var/pretix/data
[database]
; Replace mysql with postgresql_psycopg2 for PostgreSQL
; Replace mysql with psycopg2 for PostgreSQL
backend=mysql
name=pretix
user=pretix
@@ -100,13 +100,13 @@ Fill the configuration file ``/etc/pretix/pretix.cfg`` with the following conten
sessions=true
[celery]
backend=redis://127.0.0.1/1
broker=redis://127.0.0.1/2
backend=redis://127.0.0.1?virtual_host=1
broker=redis://127.0.0.1?virtual_host=2
See :ref:`email configuration <mail-settings>` to learn more about configuring mail features.
Install pretix from PyPI
------------------------
Install pretix from source
--------------------------
Now we will install pretix itself. The following steps are to be executed as the ``pretix`` user. Before we
actually install pretix, we will create a virtual environment to isolate the python packages from your global
@@ -116,13 +116,14 @@ python installation::
$ source /var/pretix/venv/bin/activate
(venv)$ pip3 install -U pip setuptools wheel
We now install pretix, its direct dependencies and gunicorn. Replace ``mysql`` with ``postgres`` in the following
command if you're running PostgreSQL::
We now clone pretix and install its Python dependencies (replace ``mysql`` with ``postgres`` if you're running
PostgreSQL)::
(venv)$ pip3 install "pretix[mysql]" gunicorn
If you are running Python 3.4, you also need to ``pip3 install typing``. This is not required on 3.5 or newer.
You can find out your Python version using ``python -V``.
(venv)$ git clone https://github.com/pretix/pretix.git /var/pretix/source
(venv)$ cd /var/pretix/source/src
(venv)$ pip3 install -r requirements.txt -r requirements/mysql.txt \
-r requirements/redis.txt \
-r requirements/py34.txt gunicorn
We also need to create a data directory::
@@ -130,8 +131,8 @@ We also need to create a data directory::
Finally, we compile static files and translation data and create the database structure::
(venv)$ python -m pretix migrate
(venv)$ python -m pretix rebuild
(venv)$ make production
(venv)$ python manage.py migrate
Start pretix as a service
@@ -153,7 +154,7 @@ named ``/etc/systemd/system/pretix-web.service`` with the following content::
--name pretix --workers 5 \
--max-requests 1200 --max-requests-jitter 50 \
--log-level=info --bind=127.0.0.1:8345
WorkingDirectory=/var/pretix
WorkingDirectory=/var/pretix/source/src
Restart=on-failure
[Install]
@@ -170,8 +171,8 @@ For background tasks we need a second service ``/etc/systemd/system/pretix-worke
Group=pretix
Environment="VIRTUAL_ENV=/var/pretix/venv"
Environment="PATH=/var/pretix/venv/bin:/usr/local/bin:/usr/bin:/bin"
ExecStart=/var/pretix/venv/bin/celery -A pretix.celery_app worker -l info
WorkingDirectory=/var/pretix
ExecStart=/var/pretix/venv/bin/celery -A pretix worker -l info
WorkingDirectory=/var/pretix/source/src
Restart=on-failure
[Install]
@@ -190,7 +191,7 @@ Cronjob
You need to set up a cronjob that runs the management command ``runperiodic``. The exact interval is not important
but should be something between every minute and every hour. You could for example configure cron like this::
15,45 * * * * export PATH=/var/pretix/venv/bin:$PATH && cd /var/pretix && python -m pretix runperiodic
15,45 * * * * export PATH=/var/pretix/venv/bin:$PATH && cd /var/pretix/source/src && ./manage.py runperiodic
The cronjob should run as the ``pretix`` user (``crontab -e -u pretix``).
@@ -213,9 +214,6 @@ The following snippet is an example on how to configure a nginx proxy for pretix
ssl_certificate /path/to/cert.chain.pem;
ssl_certificate_key /path/to/key.pem;
add_header Referrer-Options same-origin;
add_header X-Content-Type-Options nosniff;
location / {
proxy_pass http://localhost:8345/;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
@@ -229,25 +227,14 @@ The following snippet is an example on how to configure a nginx proxy for pretix
access_log off;
}
location ^~ /media/cachedfiles {
deny all;
return 404;
}
location ^~ /media/invoices {
deny all;
return 404;
}
location /static/ {
alias /var/pretix/venv/lib/python3.5/site-packages/pretix/static.dist/;
alias /var/pretix/source/src/pretix/static.dist/;
access_log off;
expires 365d;
add_header Cache-Control "public";
}
}
.. note:: Remember to replace the ``python3.5`` in the ``/static/`` path in the config
above with your python version.
We recommend reading about setting `strong encryption settings`_ for your web server.
@@ -258,8 +245,6 @@ Yay, you are done! You should now be able to reach pretix at https://pretix.your
*admin@localhost* with a password of *admin*. Don't forget to change that password! Create an organizer first, then
create an event and start selling tickets!
You should probably read :ref:`maintainance` next.
Updates
-------
@@ -269,27 +254,16 @@ To upgrade to a new pretix release, pull the latest code changes and run the fol
``mysql`` with ``postgres`` if necessary)::
$ source /var/pretix/venv/bin/activate
(venv)$ pip3 install -U pretix[mysql] gunicorn
(venv)$ python -m pretix migrate
(venv)$ python -m pretix rebuild
(venv)$ python -m pretix updatestyles
(venv)$ cd /var/pretix/source/src
(venv)$ git pull origin master
(venv)$ pip3 install -r requirements.txt -r requirements/mysql.txt \
-r requirements/redis.txt \
-r requirements/py34.txt gunicorn
(venv)$ python manage.py migrate
(venv)$ make production
(venv)$ python manage.py updatestyles
# systemctl restart pretix-web pretix-worker
Install a plugin
----------------
To install a plugin, just use ``pip``! Depending on the plugin, you should probably apply database migrations and
rebuild the static files afterwards. Replace ``pretix-passbook`` with the plugin of your choice in the following
example::
$ source /var/pretix/venv/bin/activate
(venv)$ pip3 install pretix-passbook
(venv)$ python -m pretix migrate
(venv)$ python -m pretix rebuild
# systemctl restart pretix-web pretix-worker
.. _Postfix: https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-postfix-as-a-send-only-smtp-server-on-ubuntu-16-04
.. _nginx: https://botleg.com/stories/https-with-lets-encrypt-and-nginx/
.. _Let's Encrypt: https://letsencrypt.org/

View File

@@ -1,99 +0,0 @@
.. highlight:: ini
.. _`maintainance`:
Backups and Monitoring
======================
If you host your own pretix instance, you also need to care about the availability
of your service and the safety of your data yourself. This page gives you some
information that you might need to do so properly.
Backups
-------
There are essentially two things which you should create backups of:
Database
Your SQL database (MySQL or PostgreSQL). This is critical and you should **absolutely
always create automatic backups of your database**. There are tons of tutorials on the
internet on how to do this, and the exact process depends on the choice of your database.
For MySQL, see ``mysqldump`` and for PostgreSQL, see the ``pg_dump`` tool. You probably
want to create a cronjob that does the backups for you on a regular schedule.
Data directory
The data directory of your pretix configuration might contain some things that you should
back up. If you did not specify a secret in your config file, back up the ``.secret`` text
file in the data directory. If you lose your secret, all currently active user sessions,
password reset links and similar things will be rendered invalid. Also, you probably want
to backup the ``media`` subdirectory of the data directory which contains all user-uploaded
and generated files. This includes files you could in theory regenerate (ticket downloads)
but also files that you might be legally required to keep (invoice PDFs) or files that you
would need to re-upload (event logos, product pictures, etc.). It is up to you if you
create regular backups of this data, but we strongly advise you to do so. You can create
backups e.g. using ``rsync``. There is a lot of information on the internet on how to create
backups of folders on a Linux machine.
There is no need to create backups of the redis database, if you use it. We only use it for
non-critical, temporary or cached data.
Uptime monitoring
-----------------
To monitor whether your pretix instance is running, you can issue a GET request to
``https://pretix.mydomain.com/healthcheck/``. This endpoint tests if the connection to the
database, to the configured cache and to redis (if used) is working correctly. If everything
appears to work fine, an empty response with status code ``200`` is returned.
If there is a problem, a status code in the ``5xx`` range will be returned.
.. _`perf-monitoring`:
Performance monitoring
----------------------
If you to generate detailled performance statistics of your pretix installation, there is an
endpoint at ``https://pretix.mydomain.com/metrics`` (no slash at the end) which returns a
number of values in the text format understood by monitoring tools like Prometheus_. This data
is only collected and exposed if you enable it in the :ref:`metrics-settings` section of your
pretix configuration. You can also configure basic auth credentials there to protect your
statistics against unauthorized access. The data is temporarily collected in redis, so the
performance impact of this feature depends on the connection to your redis database.
Currently, mostly response times of HTTP requests and background tasks are exposed.
If you want to go even further, you can set the ``profile`` option in the :ref:`django-settings`
section to a value between 0 and 1. If you set it for example to 0.1, then 10% of your requests
(randomly selected) will be run with cProfile_ activated. The profiling results will be saved
to your data directory. As this might impact performance significantly and writes a lot of data
to disk, we recommend to only enable it for a small number of requests -- and only if you are
really interested in the results.
Available metrics
^^^^^^^^^^^^^^^^^
The metrics available in pretix follow the standard `metric types`_ from the Prometheus world.
Currently, the following metrics are exported:
pretix_view_requests_total
Counter. Counts requests to Django views, labeled with the resolved ``url_name``, the used
HTTP ``method`` and the ``status_code`` returned.
pretix_view_durations_seconds
Histogram. Measures duration of requests to Django views, labeled with the resolved
``url_name``, the used HTTP ``method`` and the ``status_code`` returned.
pretix_task_runs_total
Counter. Counts executions of background tasks, labeled with the ``task_name`` and the
``status``. The latter can be ``success``, ``error`` or ``expected-error``.
pretix_task_duration_seconds
Histogram. Measures duration of successful background task executions, labeled with the
``task_name``.
pretix_model_instances
Gauge. Measures number of instances of a certain model within the database, labeled with
the ``model`` name.
.. _metric types: https://prometheus.io/docs/concepts/metric_types/
.. _Prometheus: https://prometheus.io/
.. _cProfile: https://docs.python.org/3/library/profile.html

View File

@@ -38,7 +38,6 @@ extensions = [
'sphinx.ext.doctest',
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinxcontrib.httpdomain',
]
# Add any paths that contain templates here, relative to this directory.
@@ -55,17 +54,16 @@ master_doc = 'index'
# General information about the project.
project = 'pretix'
copyright = '2014-2017, Raphael Michel'
copyright = '2014-2016, Raphael Michel'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
from pretix import __version__
version = '.'.join(__version__.split('.')[:2])
version = '0.0.0'
# The full version, including alpha/beta/rc tags.
release = __version__
release = '0.0.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.

View File

@@ -11,7 +11,7 @@ Core
----
.. automodule:: pretix.base.signals
:members: periodic_task, event_live_issues, event_copy_data
:members: periodic_task
Order events
""""""""""""
@@ -19,13 +19,13 @@ Order events
There are multiple signals that will be sent out in the ordering cycle:
.. automodule:: pretix.base.signals
:members: validate_cart, order_paid, order_placed
:members: order_paid, order_placed
Frontend
--------
.. automodule:: pretix.presale.signals
:members: html_head, html_footer, footer_links, front_page_top, front_page_bottom, checkout_confirm_messages
:members: html_head, footer_links, front_page_top, front_page_bottom
.. automodule:: pretix.presale.signals
@@ -47,11 +47,11 @@ Backend
-------
.. automodule:: pretix.control.signals
:members: nav_event, html_head, quota_detail_html, nav_topbar, nav_global, nav_organizer
:members: nav_event, html_head, quota_detail_html
.. automodule:: pretix.base.signals
:members: logentry_display, requiredaction_display
:members: logentry_display
Vouchers
""""""""

View File

@@ -70,6 +70,8 @@ The provider class
.. automethod:: is_allowed
.. automethod:: is_allowed_for_order
.. autoattribute:: payment_form_fields
.. automethod:: checkout_prepare

View File

@@ -42,13 +42,6 @@ configuration class. The metadata class must define the following attributes:
``description`` (``str``):
A more verbose description of what your plugin does.
``visible`` (``bool``):
``True`` by default, can hide a plugin so it cannot be normally activated.
``restricted`` (``bool``):
``False`` by default, restricts a plugin such that it can only be enabled for an event
by system administrators / superusers.
A working example would be::
# file: pretix/plugins/timerestriction/__init__.py
@@ -64,8 +57,6 @@ A working example would be::
name = _("PayPal")
author = _("the pretix team")
version = '1.0.0'
visible = True
restricted = False
description = _("This plugin allows you to receive payments via PayPal")

View File

@@ -64,6 +64,6 @@ The output class
.. automethod:: generate
.. automethod:: generate_order
.. autoattribute:: download_button_text
.. autoattribute:: download_button_icon

View File

@@ -18,9 +18,8 @@ If you improved pretix in any way, we'd be very happy if you contribute it
back to the main code base! The easiest way to do so is to `create a pull request`_
on our `GitHub repository`_.
We recommend that you create a feature branch for every issue you work on so the changes can
be reviewed individually.
Please use the test suite to check whether your changes break any existing features and run
Before you do so, please `squash all your changes`_ into one single commit. Please
use the test suite to check whether your changes break any existing features and run
the code style checks to confirm you are consistent with pretix's coding style. You'll
find instructions on this in the :ref:`checksandtests` section of the development setup guide.
@@ -35,3 +34,4 @@ Again: If you get stuck, do not hesitate to contact any of us, or Raphael person
.. _create a pull request: https://help.github.com/articles/creating-a-pull-request/
.. _GitHub repository: https://github.com/pretix/pretix
.. _squash all your changes: https://davidwalsh.name/squash-commits-git

View File

@@ -8,12 +8,12 @@ Python code
Use `flake8`_ to check for conformance problems. The project includes a setup.cfg file
with a default configuration for flake8 that excludes migrations and other non-relevant
code parts. It also silences a few checks, e.g. ``N802`` (function names should be lowercase)
and increases the maximum line length to more than 79 characters. **However** you should
code parts. It also silences a few checks, e.g. ``N802`` (function names should be lowercase)
and increases the maximum line length to more than 79 characters. **However** you should
still name all your functions lowercase [#f1]_ and keep your lines short when possible.
* Our build server will reject all code violating other flake8 checks than the following:
* E123: closing bracket does not match indentation of opening brackets line
* F403: ``from module import *`` used; unable to detect undefined names
* F401: module imported but unused

View File

@@ -6,18 +6,116 @@ One of pretix's major selling points is its multi-language capability. We make h
way to translate *user-generated content*. In our case, we need to translate strings like product names
or event descriptions, so we need event organizers to be able to fill in all fields in multiple languages.
For this purpose, we use ``django-i18nfield`` which started out as part of pretix and then got refactored into
its own library. It has comprehensive documentation on how to work with its `strings`_, `database fields`_ and
`forms`_.
.. note:: Implementing object-level translation in a relational database is a task that requires some difficult
trade-off. We decided for a design that is not elegant on the database level (as it violates the `1NF`_) and
makes searching in the respective database fields very hard, but allows for a simple design on the ORM level
and adds only minimal performance overhead.
All classes and functions introduced in this document are located in ``pretix.base.i18n`` if not stated otherwise.
Database storage
----------------
pretix provides two custom model field types that allow you to work with localized strings: ``I18nCharField`` and
``I18nTextField``. Both of them are stored in the database as a ``TextField`` internally, they only differ in the
default form widget that is used by ``ModelForm``.
As pretix does not use these fields in places that need to be searched, the negative performance impact when searching
and indexing these fields in negligible, as mentioned above. Lookups are currently not even implemented on these
fields. In the database, the strings will be stored as a JSON-encoded mapping of language codes to strings.
Whenever you interact with those fields, you will either provide or receive an instance of the following class:
.. autoclass:: pretix.base.i18n.LazyI18nString
:members: __init__, localize, __str__
Usage
-----
The following examples are given to illustrate how you can work with ``LazyI18nString``.
.. testsetup:: *
from pretix.base.i18n import LazyI18nString, language
To create a LazyI18nString, we can cast a simple string:
.. doctest::
>>> naive = LazyI18nString('Naive untranslated string')
>>> naive
<LazyI18nString: 'Naive untranslated string'>
Or we can provide a dictionary with multiple translations:
.. doctest::
>>> translated = LazyI18nString({'en': 'English String', 'de': 'Deutscher String'})
We can use ``localize`` to get the string in a specific language:
.. doctest::
>>> translated.localize('de')
'Deutscher String'
>>> translated.localize('en')
'English String'
If we try a locale that does not exist for the string, we might get a it either in a similar locale or in the system's default language:
.. doctest::
>>> translated.localize('de-AT')
'Deutscher String'
>>> translated.localize('zh')
'English String'
>>> naive.localize('de')
'Naive untranslated string'
If we cast a ``LazyI18nString`` to ``str``, ``localize`` will be called with the currently active language:
.. doctest::
>>> from django.utils import translation
>>> str(translated)
'English String'
>>> translation.activate('de')
>>> str(translated)
'Deutscher String'
You can also use our handy context manager to set the locale temporarily:
.. doctest::
>>> translation.activate('en')
>>> with language('de'):
... str(translated)
'Deutscher String'
>>> str(translated)
'English String'
Forms
-----
For backwards-compatibility with older parts of pretix' code base and older plugins, ``pretix.base.forms`` still
contains a number of forms that are equivalent in name and usage to their counterparts in ``i18nfield.forms`` with
the difference that they take an ``event`` keyword argument and then set the ``locales`` argument based on
``event.settings.get('locales')``.
We provide i18n-aware versions of the respective form fields and widgets: ``I18nFormField`` with the ``I18nTextInput``
and ``I18nTextarea`` widgets. They transparently allow you to use ``LazyI18nString`` values in forms and render text
inputs for multiple languages.
.. autoclass:: pretix.base.i18n.I18nFormField
To easily limit the displayed languages to the languages relevant to an event, there is a custom ``ModelForm`` subclass
that deals with this for you:
.. autoclass:: pretix.base.forms.I18nModelForm
There are equivalents for ``BaseModelFormSet`` and ``BaseInlineFormSet``:
.. autoclass:: pretix.base.forms.I18nFormSet
.. autoclass:: pretix.base.forms.I18nInlineFormSet
Useful utilities
----------------
@@ -37,6 +135,4 @@ action that causes the mail to be sent.
.. _translation features: https://docs.djangoproject.com/en/1.9/topics/i18n/translation/
.. _GNU gettext: https://www.gnu.org/software/gettext/
.. _strings: https://django-i18nfield.readthedocs.io/en/latest/strings.html
.. _database fields: https://django-i18nfield.readthedocs.io/en/latest/quickstart.html
.. _forms: https://django-i18nfield.readthedocs.io/en/latest/forms.html
.. _1NF: https://en.wikipedia.org/wiki/First_normal_form

View File

@@ -20,13 +20,13 @@ Organizers and events
.. autoclass:: pretix.base.models.Organizer
:members:
.. autoclass:: pretix.base.models.OrganizerPermission
:members:
.. autoclass:: pretix.base.models.Event
:members:
.. autoclass:: pretix.base.models.Team
:members:
.. autoclass:: pretix.base.models.RequiredAction
.. autoclass:: pretix.base.models.EventPermission
:members:
@@ -66,9 +66,6 @@ Carts and Orders
.. autoclass:: pretix.base.models.QuestionAnswer
:members:
.. autoclass:: pretix.base.models.Checkin
:members:
Logging
-------
@@ -89,3 +86,5 @@ Vouchers
.. autoclass:: pretix.base.models.Voucher
:members:
.. _cleanerversion: https://github.com/swisscom/cleanerversion

View File

@@ -2,10 +2,7 @@ Settings storage
================
pretix is highly configurable and therefore needs to store a lot of per-event and per-organizer settings.
For this purpose, we use `django-hierarkey`_ which started out as part of pretix and then got refactored into
its own library. It has a comprehensive `documentation`_ which you should read if you work with settings in pretix.
The settings are stored in the database and accessed through a ``HierarkeyProxy`` instance. You can obtain
Those settings are stored in the database and accessed through a ``SettingsProxy`` instance. You can obtain
such an instance from any event or organizer model instance by just accessing ``event.settings`` or
``organizer.settings``, respectively.
@@ -20,10 +17,12 @@ includes serializers for serializing the following types:
In code, we recommend to always use the ``.get()`` method on the settings object to access a value, but for
convenience in templates you can also access settings values at ``settings[name]`` and ``settings.name``.
See the hierarkey `documentation`_ for more information.
.. autoclass:: pretix.base.settings.SettingsProxy
:members: get, set, delete, freeze
To avoid naming conflicts, plugins are requested to prefix all settings they use with the name of the plugin
or something unique, e.g. ``payment_paypal_api_key``. To reduce redundant typing of this prefix, we provide
or something unique, e.g. ``payment.paypal.api_key``. To reduce redundant typing of this prefix, we provide
another helper class:
.. autoclass:: pretix.base.settings.SettingsSandbox
@@ -34,10 +33,10 @@ you will just be passed a sandbox object with a prefix generated from your provi
Forms
-----
Hierarkey also provides a base class for forms that allow the modification of settings. pretix contains a
subclass that also adds suport for internationalized fields:
We also provide a base class for forms that allow the modification of settings:
.. autoclass:: pretix.base.forms.SettingsForm
:members: save
You can simply use it like this::
@@ -52,17 +51,3 @@ You can simply use it like this::
help_text=_("The number of days after placing an order the user has to pay to "
"preserve his reservation."),
)
Defaults in plugins
-------------------
Plugins can add custom hardcoded defaults in the following way::
from pretix.base.settings import settings_hierarkey
settings_hierarkey.add_default('key', 'value', type)
Make sure that you include this code in a module that is imported at app loading time.
.. _django-hierarkey: https://github.com/raphaelm/django-hierarkey
.. _documentation: https://django-hierarkey.readthedocs.io/en/latest/

View File

@@ -15,12 +15,8 @@ External Dependencies
* Python 3.4 or newer
* ``pip`` for Python 3 (Debian package: ``python3-pip``)
* ``pyvenv`` for Python 3 (Debian package: ``python3-venv``)
* ``python-dev`` for Python 3 (Debian package: ``python3-dev``)
* ``libffi`` (Debian package: ``libffi-dev``)
* ``libssl`` (Debian package: ``libssl-dev``)
* ``libxml2`` (Debian package ``libxml2-dev``)
* ``libxslt`` (Debian package ``libxslt1-dev``)
* ``msgfmt`` (Debian package ``gettext``)
* ``git``
Your local python environment
@@ -81,11 +77,7 @@ and head to http://localhost:8000/
As we did not implement an overall front page yet, you need to go directly to
http://localhost:8000/control/ for the admin view or, if you imported the test
data as suggested above, to the event page at http://localhost:8000/bigevents/2017/
.. note:: If you want the development server to listen on a different interface or
port (for example because you develop on `pretixdroid`_), you can check
`Django's documentation`_ for more options.
data as suggested above, to the event page at http://localhost:8000/mrmcd/2015/
.. _`checksandtests`:
@@ -126,8 +118,8 @@ Then execute ``python -m smtpd -n -c DebuggingServer localhost:1025``.
Working with translations
^^^^^^^^^^^^^^^^^^^^^^^^^
If you want to translate new strings that are not yet known to the translation system,
you can use the following command to scan the source code for strings to be translated
If you want to translate new strings that are not yet known to the translation system,
you can use the following command to scan the source code for strings to be translated
and update the ``*.po`` files accordingly::
make localegen
@@ -152,7 +144,3 @@ To build the documentation, run the following command from the ``doc/`` director
make html
You will now find the generated documentation in the ``doc/_build/html/`` subdirectory.
.. _Django's documentation: https://docs.djangoproject.com/en/1.11/ref/django-admin/#runserver
.. _pretixdroid: https://github.com/pretix/pretixdroid

View File

@@ -26,11 +26,8 @@ pretix/
multidomain/
Additional code implementing our customized :ref:`URL handling <urlconf>`.
static/
Contains all static files (CSS, JavaScript, images)
static/
Contains some pretix plugins that ship with pretix itself
static/
Contains all static files (CSS, JavaScript, images)
tests/
This is the root directory for all test codes. It includes subdirectories ``base``,
@@ -40,8 +37,7 @@ tests/
Language files
--------------
The language files live in ``pretix/locale/*/LC_MESSAGES/``.
The language files live in ``locale/*/LC_MESSAGES/``.
Static files
------------
@@ -53,14 +49,27 @@ We use libsass as a preprocessor for CSS. Our own sass code is built in the same
step as Bootstrap and FontAwesome, so their mixins etc. are fully available.
pretix.control
pretixcontrol has two main SCSS files, ``pretix/static/pretixcontrol/scss/main.scss`` and
``pretix/static/pretixcontrol/scss/auth.scss``, importing everything else.
pretixcontrol has two main SCSS files, ``pretix/control/static/pretixcontrol/scss/main.scss`` and
``pretix/control/static/pretixcontrol/scss/auth.scss``, importing everything else.
pretix.presale
pretixpresale has one main SCSS files, ``pretix/pretixpresale/scss/main.scss``,
pretixpresale has one main SCSS files, ``pretix/control/static/pretix/presale/scss/main.scss``,
importing everything else.
3rd-party assets
^^^^^^^^^^^^^^^^
Most client-side 3rd-party assets are vendored in various subdirectories of ``pretix/static``.
Bootstrap
Bootstrap lives vendored at ``static/bootstrap/``
Font Awesome
Font Awesome lives vendored at ``static/fontawesome/``
jQuery
jQuery lives as a single JavaScript file in ``static/jquery/js/``
jQuery plugin: Django formsets
Our own modified version of `django-formset-js`_ is available as an independent
django app and installed via ``pip``.
.. _django-formset-js: https://github.com/pretix/django-formset-js

View File

@@ -6,8 +6,6 @@ Contents:
.. toctree::
:maxdepth: 2
user/index
admin/index
development/index
plugins/index

View File

@@ -1,13 +0,0 @@
Plugin documentation
====================
This part of the documentation contains information about available plugins
that can be used to extend pretix's functionality.
If you want to **create** a plugin, please go to the
:ref:`Developer documentation <pluginsetup>` instead.
.. toctree::
:maxdepth: 2
list
pretixdroid

View File

@@ -1,38 +0,0 @@
List of plugins
===============
The following plugins are shipped with pretix and are supported in the same
ways that pretix itself is:
* Bank transfer
* PayPal
* Stripe
* Check-in lists
* pretixdroid
* Report exporter
* Send out emails
* Statistics
* PDF ticket output
The following plugins are not shipped with pretix but are maintained by the
same team:
* `SEPA direct debit`_
* `Pages`_
* `Passbook/Wallet ticket output`_
* `Cartshare`_
* `Fontpack Free fonts`_
The following plugins are from independent third-party authors, so we can make
no statements about their stability:
* `esPass ticket output`_
* `IcePay integration`_
.. _SEPA direct debit: https://github.com/pretix/pretix-sepadebit
.. _Passbook/Wallet ticket output: https://github.com/pretix/pretix-passbook
.. _Cartshare: https://github.com/pretix/pretix-cartshare
.. _Pages: https://github.com/pretix/pretix-pages
.. _esPass ticket output: https://github.com/esPass/pretix-espass
.. _IcePay integration: https://github.com/chotee/pretix-icepay
.. _Fontpack Free fonts: https://github.com/pretix/pretix-fontpack-free

View File

@@ -1,228 +0,0 @@
pretixdroid HTTP API
====================
The pretixdroid plugin provides a HTTP API that the `pretixdroid Android app`_
uses to communicate with the pretix server.
.. warning:: This API is intended **only** to serve the pretixdroid Android app. There are no backwards compatibility
guarantees on this API. We will not add features that are not required for the Android App. There will be
a proper general-use API for pretix at a later point in time.
.. http:post:: /pretixdroid/api/(organizer)/(event)/redeem/
Redeems a ticket, i.e. checks the user in.
**Example request**:
.. sourcecode:: http
POST /pretixdroid/api/demoorga/democon/redeem/?key=ABCDEF HTTP/1.1
Host: demo.pretix.eu
Accept: application/json, text/javascript
Content-Type: application/x-www-form-urlencoded
secret=az9u4mymhqktrbupmwkvv6xmgds5dk3
You can optionally include the additional parameter ``datetime`` in the body containing an ISO8601-encoded
datetime of the entry attempt. If you don't, the current date and time will be used.
You can optionally include the additional parameter ``force`` to indicate that the request should be logged
regardless of previous check-ins for the same ticket. This might be useful if you made the entry decision offline.
You can optionally include the additional parameter ``nonce`` with a globally unique random value to identify this
check-in. This is meant to be used to prevent duplicate check-ins when you are just retrying after a connection
failure.
**Example successful response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: text/json
{
"status": "ok"
"version": 2
}
**Example error response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: text/json
{
"status": "error",
"reason": "already_redeemed",
"version": 2
}
Possible error reasons:
* ``unpaid`` - Ticket is not paid for or has been refunded
* ``already_redeemed`` - Ticket already has been redeemed
* ``unknown_ticket`` - Secret does not match a ticket in the database
:query key: Secret API key
:statuscode 200: Valid request
:statuscode 404: Unknown organizer or event
:statuscode 403: Invalid authorization key
.. http:get:: /pretixdroid/api/(organizer)/(event)/search/
Searches for a ticket.
At most 25 results will be returned. **Queries with less than 4 characters will always return an empty result set.**
**Example request**:
.. sourcecode:: http
GET /pretixdroid/api/demoorga/democon/search/?key=ABCDEF&query=Peter HTTP/1.1
Host: demo.pretix.eu
Accept: application/json, text/javascript
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: text/json
{
"results": [
{
"secret": "az9u4mymhqktrbupmwkvv6xmgds5dk3",
"order": "ABCE6",
"item": "Standard ticket",
"variation": null,
"attendee_name": "Peter Higgs",
"redeemed": false,
"paid": true
},
...
],
"version": 2
}
:query query: Search query
:query key: Secret API key
:statuscode 200: Valid request
:statuscode 404: Unknown organizer or event
:statuscode 403: Invalid authorization key
.. http:get:: /pretixdroid/api/(organizer)/(event)/download/
Download data for all tickets.
**Example request**:
.. sourcecode:: http
GET /pretixdroid/api/demoorga/democon/download/?key=ABCDEF HTTP/1.1
Host: demo.pretix.eu
Accept: application/json, text/javascript
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: text/json
{
"results": [
{
"secret": "az9u4mymhqktrbupmwkvv6xmgds5dk3",
"order": "ABCE6",
"item": "Standard ticket",
"variation": null,
"attendee_name": "Peter Higgs",
"redeemed": false,
"paid": true
},
...
],
"version": 2
}
:query key: Secret API key
:statuscode 200: Valid request
:statuscode 404: Unknown organizer or event
:statuscode 403: Invalid authorization key
.. http:get:: /pretixdroid/api/(organizer)/(event)/status/
Returns status information, such as the total number of tickets and the
number of performed checkins.
**Example request**:
.. sourcecode:: http
GET /pretixdroid/api/demoorga/democon/status/?key=ABCDEF HTTP/1.1
Host: demo.pretix.eu
Accept: application/json, text/javascript
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: text/json
{
"checkins": 17,
"total": 42,
"version": 2,
"event": {
"name": "Demo Converence",
"slug": "democon",
"date_from": "2016-12-27T17:00:00Z",
"date_to": "2016-12-30T18:00:00Z",
"timezone": "UTC",
"url": "https://demo.pretix.eu/demoorga/democon/",
"organizer": {
"name": "Demo Organizer",
"slug": "demoorga"
},
},
"items": [
{
"name": "T-Shirt",
"id": 1,
"checkins": 1,
"admission": False,
"total": 1,
"variations": [
{
"name": "Red",
"id": 1,
"checkins": 1,
"total": 12
},
{
"name": "Blue",
"id": 2,
"checkins": 4,
"total": 8
}
]
},
{
"name": "Ticket",
"id": 2,
"checkins": 15,
"admission": True,
"total": 22,
"variations": []
}
]
}
:query key: Secret API key
:statuscode 200: Valid request
:statuscode 404: Unknown organizer or event
:statuscode 403: Invalid authorization key
.. _pretixdroid Android app: https://github.com/pretix/pretixdroid

View File

@@ -1,4 +1,3 @@
-r ../src/requirements.txt
sphinx
sphinx-rtd-theme
sphinxcontrib-httpdomain

View File

@@ -1,9 +0,0 @@
User Guide
==========
Contents:
.. toctree::
:maxdepth: 2
payments/index

View File

@@ -1,31 +0,0 @@
.. _`banktransfer`:
Bank transfer
=============
To accept payments with bank transfer, you only need to fill one important field in pretix' settings: In "Bank
account details" you should specify everything one needs to know to transfer money to you, e.g. your IBAN and BIC,
the name of your bank and for international transfers, preferably also your address and the bank's address.
pretix will automatically tell the user to include the order code in the payment reference so incoming transfers can
automatically be matched to payments.
Importing payment data
----------------------
The easiest way to import payment data is to download a CSV file from your online banking. Most banks provide a CSV
export of some sort. You can go to "Import bank data" in pretix to upload a new file:
.. image:: img/bank1.png
If you upload a file for the first time, pretix will not know what information is contained in which column as every
bank builds completely different CSV files. Therefore, pretix will ask you for that information. It will show you the
data of the file you imported and ask you to define the column's meanings. You can select one column that contains
the payment date and one that contains the paid amount. You can select multiple columns that contain information
about the payer or the payment reference. All other columns will be ignored.
Once you continue, pretix will try to match the payments to the respective orders automatically. It will tell you how
many orders could be processed correctly and how many could not. You can then go back to the upload page to see all
transfers from your bank statement that are not yet matched to an order. Using the input field and the buttons on the
left of each transaction, you can manually enter an order code to match it to or just discard it from the list, e.g.
if the transaction is not related to the event at all.

View File

@@ -1,52 +0,0 @@
Payment method fees
===================
Most external payment providers like PayPal or Stripe charge substantial fees for your service. In general, you have
two options to deal with this:
1. Pay the fees yourself
2. Add the fees to your customer's total
The choice totally depends on you and what your customers expect from you. Option two might be appropriate if you
offer different payment methods and want to encourage your customers to use the ones that come you cheaper, but you
might also decide to go for option one to make it easier for customers who don't have the option.
If you go for the second option, you can configure pretix to charge the payment method fees to your user. You can
define both an absolute fee as well as a percental fee based on the order total. If you do so, there are two
different ways in which pretix can calculate the fee. Normally, it is fine to just go with the default setting, but
in case you are interested, here are all the details:
Payment fee calculation
-----------------------
If you configure a fee for a payment method, there are two possible ways for us to calculate this. Let's
assume that your payment provider, e.g. PayPal, charges you 5 % fees and you want to charge your users the
same 5 %, such that for a ticket with a list price of 100 € you will get your full 100 €.
**Method A: Calculate the fee from the subtotal and add it to the bill.**
For a ticket price of 100 €, this will lead to the following calculation:
============================================== ============
Ticket price 100.00 €
pretix calculates the fee as 5 % of 100 € +5.00 €
Subtotal that will be paid by the customer 105.00 €
PayPal calculates its fee as 5 % of 105 € -5.25 €
End total that is on your bank account **99.75 €**
============================================== ============
**Method B (default): Calculate the fee from the total value including the fee.**
For a ticket price of 100 €, this will lead to the following calculation:
===================================================== =============
Ticket price 100.00 €
pretix calculates the fee as 100/(100 - 5) % of 100 € +5.26 €
Subtotal that will be paid by the customer 105.26 €
PayPal calculates its fee as 5 % of 105 € -5.26 €
End total that is on your bank account **100.00 €**
===================================================== =============
Due to the various rounding steps performed by pretix and by the payment provider, the end total on
your bank account might stil vary by one cent.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 105 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 81 KiB

View File

@@ -1,14 +0,0 @@
Accepting payments
==================
Contents:
.. toctree::
:maxdepth: 2
overview
fees
paypal
stripe
banktransfer

View File

@@ -1,34 +0,0 @@
Payment method overview
=======================
pretix allows you to accept payments using a variety of payment methods to fit the needs of very different events.
This page gives you a short overview over them and links to more detailled descriptions in some cases.
Payment methods are built as pretix plugins. For this reason, you might first need to enable a certain plugin at
"Settings" → "Plugins" in your event settings. Then, you can configure them in detail at "Settings" -> "Payment".
If you host pretix on your own server, you might need to install a plugin first for some of the payment methods listed
on this page as well as for additional ones.
:ref:`stripe`
Stripe is a US-based company that offers you an easy way to accept credit card payments from all over the world.
To accept payments with Stripe, you need to have a Stripe merchant account that is easy to create. Click on the link
above to get more details about the Stripe integration into pretix.
:ref:`paypal`
If you want to accept online payments via PayPal, you can do so using pretix. You will need a PayPal merchant
account and it is a little bit complicated to obtain the required technical details, but we've got you covered.
Click on the link above to learn more.
:ref:`banktransfer`
Classical IBAN wire transfers are a common payment method in central Europe that has the large benefit that it
often does not cause any additional fees. However, it requires you to invest some more effort as you need to
check your bank account for incoming payments regularly. We provide some tools to make this easier for you.
SEPA debit
In some Europen countries, a very popular online payment method is SEPA direct debit. If you want to offer this
option in your pretix ticket shop, we provide a convenient plugin that allows users to enter their SEPA bank
account details and issue a SEPA mandate. You will then need to regularly download a SEPA XML file from pretix
and upload it to your bank's interface to actually perform the debits.

View File

@@ -1,50 +0,0 @@
.. _`paypal`:
PayPal
======
To integrate PayPal with pretix, you first need to have an active PayPal merchant account. If you do not already have a
PayPal account, you can create one on `paypal.com`_.
If you look into pretix' settings, you are required to fill in two keys:
.. image:: img/paypal_pretix.png
Unfortunately, it is not straightforward how to get those keys from PayPal's website. In order to do so, you
need to go to `developer.paypal.com`_ to link the account to your pretix event.
Click on "Log In" in the top-right corner and log in with your PayPal account.
.. image:: img/paypal2.png
Then, click on "Dashboard" in the top-right corner.
.. image:: img/paypal3.png
In the dashboard, scroll down until you see the headline "REST API Apps". Click "Create App".
.. image:: img/paypal4.png
Enter any name for the application that helps you to identify it later. Then confirm with "Create App".
.. image:: img/paypal5.png
On the next page, before you do anything else, switch the mode on the right to "Live" to get the correct keys.
Then, copy the "Client ID" and the "Secret" and enter them into the appropriate fields in the payment settings in
pretix.
.. image:: img/paypal6.png
Finally, we need to create a webhook. The webhook tells PayPal to notify pretix e.g. if a payment gets cancelled so
pretix can cancel the ticket as well. If you have multiple events connected to your PayPal account, you need multiple
webhooks. To create one, scroll a bit down and click "Add Webhook".
.. image:: img/paypal7.png
Then, enter the webhook URL that you find on the pretix settings page. It should look similar to the one in the
screenshot but contain your event name. Tick the box "All events" and save.
.. image:: img/paypal8.png
That's it, you are ready to go!
.. _paypal.com: https://www.paypal.com/webapps/mpp/account-selection
.. _developer.paypal.com: https://developer.paypal.com/

View File

@@ -1,28 +0,0 @@
.. _stripe:
Stripe
======
To integrate Stripe with pretix, you first need to have an active Stripe merchant account. If you do not already have a
Stripe account, you can create one on `stripe.com`_. Then, click on "API" in the left navigation of the Stripe
Dashboard. As you can see in the following screenshot, you will be presented with two sets of API keys, one for test
and one for live payments. In each set, there is a secret and a publishable keys.
.. image:: img/stripe1.png
Choose one of the two sets and copy the two keys to the appropriate fields in pretix' settings. To perform actual
payments, you will need to use the live keys, but you can use the test keys to test the payment flow before you go live.
In test mode, you cannot use your real credit card, but only `test cards`_ like ``4242424242424242`` that you can
find in Stripe's documentation.
If you want Stripe to notify pretix automatically once a payment gets cancelled, so pretix can cancel the ticket as
well, you need to create a so-called webhook. To do so, click "Webhooks" on top of the page in the Stripe dashboard
that you are currently on. Then, click "Add endpoint" and enter the URL that you find directly below the key
configuration in pretix' settings.
.. image:: img/stripe2.png
Again, you can choose between live mode and test mode here.
.. _stripe.com: https://dashboard.stripe.com/register
.. _test cards: https://stripe.com/docs/testing#cards

3
src/.gitignore vendored
View File

@@ -7,4 +7,5 @@ build/
dist/
*.egg-info/
*.bak
pretix/static/jsi18n/
static/jsi18n/

View File

@@ -1,13 +1,11 @@
include LICENSE
include README.rst
recursive-include pretix/static *
recursive-include pretix/static.dist *
recursive-include pretix/locale *
recursive-include pretix/base/templates *
recursive-include pretix/control/templates *
recursive-include pretix/presale/templates *
recursive-include pretix/plugins/banktransfer/templates *
recursive-include pretix/plugins/banktransfer/static *
recursive-include pretix/plugins/paypal/templates *
recursive-include pretix/plugins/pretixdroid/templates *
recursive-include pretix/plugins/pretixdroid/static *
@@ -16,5 +14,3 @@ recursive-include pretix/plugins/statistics/templates *
recursive-include pretix/plugins/statistics/static *
recursive-include pretix/plugins/stripe/templates *
recursive-include pretix/plugins/stripe/static *
recursive-include pretix/plugins/ticketoutputpdf/templates *
recursive-include pretix/plugins/ticketoutputpdf/static *

View File

@@ -6,7 +6,7 @@ localecompile:
localegen:
./manage.py makemessages --all --ignore "pretix/helpers/*"
./manage.py makemessages --all -d djangojs --ignore "pretix/helpers/*" --ignore "pretix/static/jsi18n/*" --ignore "pretix/static/jsi18n/*" --ignore "pretix/static.dist/*" --ignore "build/*"
./manage.py makemessages --all -d djangojs --ignore "pretix/helpers/*"
staticfiles: jsi18n
./manage.py collectstatic --noinput

View File

@@ -23,6 +23,9 @@ user.save()
organizer = Organizer.objects.create(
name='BigEvents LLC', slug='bigevents'
)
OrganizerPermission.objects.get_or_create(
organizer=organizer, user=user
)
year = now().year + 1
event = Event.objects.create(
organizer=organizer, name='Demo Conference {}'.format(year),
@@ -30,17 +33,13 @@ event = Event.objects.create(
date_from=datetime(year, 9, 4, 17, 0, 0),
date_to=datetime(year, 9, 6, 17, 0, 0),
)
t = Team.objects.get_or_create(
organizer=organizer, name='Admin Team',
all_events=True, can_create_events=True, can_change_teams=True,
can_change_organizer_settings=True, can_change_event_settings=True, can_change_items=True,
can_view_orders=True, can_change_orders=True, can_view_vouchers=True, can_change_vouchers=True
EventPermission.objects.get_or_create(
event=event, user=user
)
t.members.add(user)
cat_tickets = ItemCategory.all.create(
cat_tickets = ItemCategory.objects.create(
event=event, name='Tickets'
)
cat_merch = ItemCategory.all.create(
cat_merch = ItemCategory.objects.create(
event=event, name='Merchandise'
)
question = Question.objects.create(

View File

@@ -1 +1 @@
__version__ = "1.4.0-dev0"
__version__ = "0.0.0"

View File

@@ -9,16 +9,12 @@ class PretixBaseConfig(AppConfig):
from . import exporter # NOQA
from . import payment # NOQA
from . import exporters # NOQA
from .services import export, mail, tickets, cart, orders, cleanup, update_check # NOQA
from .services import export, mail, tickets, cart, orders, cleanup # NOQA
try:
from .celery_app import app as celery_app # NOQA
from .celery import app as celery_app # NOQA
except ImportError:
pass
default_app_config = 'pretix.base.PretixBaseConfig'
try:
import pretix.celery_app as celery # NOQA
except ImportError:
pass

View File

@@ -3,7 +3,7 @@ import tempfile
from zipfile import ZipFile
from django.dispatch import receiver
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ugettext as _
from ..exporter import BaseExporter
from ..services.invoices import invoice_pdf_task

View File

@@ -68,9 +68,7 @@ class JSONExporter(BaseExporter):
'variation': position.variation_id,
'price': position.price,
'attendee_name': position.attendee_name,
'attendee_email': position.attendee_email,
'secret': position.secret,
'addon_to': position.addon_to_id,
'answers': [
{
'question': answer.question_id,

View File

@@ -2,9 +2,7 @@ from collections import OrderedDict
from django import forms
from django.dispatch import receiver
from django.utils.translation import ugettext_lazy as _
from pretix.base.models import OrderPosition
from django.utils.translation import ugettext as _
from ..exporter import BaseExporter
from ..models import Order
@@ -18,11 +16,7 @@ class MailExporter(BaseExporter):
def render(self, form_data: dict):
qs = self.event.orders.filter(status__in=form_data['status'])
addrs = qs.values('email')
pos = OrderPosition.objects.filter(
order__event=self.event, order__status__in=form_data['status']
).values('attendee_email')
data = "\r\n".join(set(a['email'] for a in addrs)
| set(a['attendee_email'] for a in pos if a['attendee_email']))
data = "\r\n".join(set(a['email'] for a in addrs))
return 'pretixemails.txt', 'text/plain', data.encode("utf-8")
@property

View File

@@ -7,8 +7,7 @@ import pytz
from django import forms
from django.db.models import Sum
from django.dispatch import receiver
from django.utils.formats import localize
from django.utils.translation import ugettext as _, ugettext_lazy
from django.utils.translation import ugettext as _
from pretix.base.models import InvoiceAddress, Order, OrderPosition
@@ -18,7 +17,7 @@ from ..signals import register_data_exporters, register_payment_providers
class OrderListExporter(BaseExporter):
identifier = 'orderlistcsv'
verbose_name = ugettext_lazy('List of orders (CSV)')
verbose_name = _('List of orders (CSV)')
@property
def export_form_fields(self):
@@ -51,7 +50,7 @@ class OrderListExporter(BaseExporter):
tz = pytz.timezone(self.event.settings.timezone)
writer = csv.writer(output, quoting=csv.QUOTE_NONNUMERIC, delimiter=",")
qs = self.event.orders.all().select_related('invoice_address').prefetch_related('invoices')
qs = self.event.orders.all().select_related('invoice_address')
if form_data['paid_only']:
qs = qs.filter(status=Order.STATUS_PAID)
tax_rates = self._get_all_tax_rates(qs)
@@ -59,7 +58,7 @@ class OrderListExporter(BaseExporter):
headers = [
_('Order code'), _('Order total'), _('Status'), _('Email'), _('Order date'),
_('Company'), _('Name'), _('Address'), _('ZIP code'), _('City'), _('Country'), _('VAT ID'),
_('Payment date'), _('Payment type'), _('Payment method fee'),
_('Payment date'), _('Payment type'), _('Payment method fee')
]
for tr in tax_rates:
@@ -69,8 +68,6 @@ class OrderListExporter(BaseExporter):
_('Tax value at {rate} % tax').format(rate=tr),
]
headers.append(_('Invoice numbers'))
writer.writerow(headers)
provider_names = {}
@@ -89,7 +86,7 @@ class OrderListExporter(BaseExporter):
for order in qs.order_by('datetime'):
row = [
order.code,
localize(order.total),
str(order.total),
order.get_status_display(),
order.email,
order.datetime.astimezone(tz).strftime('%Y-%m-%d'),
@@ -110,7 +107,7 @@ class OrderListExporter(BaseExporter):
row += [
order.payment_date.astimezone(tz).strftime('%Y-%m-%d') if order.payment_date else '',
provider_names.get(order.payment_provider, order.payment_provider),
localize(order.payment_fee)
str(order.payment_fee)
]
for tr in tax_rates:
@@ -120,12 +117,11 @@ class OrderListExporter(BaseExporter):
taxrate_values['taxsum'] += order.payment_fee_tax_value
row += [
localize(taxrate_values['grosssum']),
localize(taxrate_values['grosssum'] - taxrate_values['taxsum']),
localize(taxrate_values['taxsum']),
str(taxrate_values['grosssum']),
str(taxrate_values['grosssum'] - taxrate_values['taxsum']),
str(taxrate_values['taxsum']),
]
row.append(', '.join([i.number for i in order.invoices.all()]))
writer.writerow(row)
return 'orders.csv', 'text/csv', output.getvalue().encode("utf-8")

View File

@@ -1,68 +1,148 @@
import logging
import i18nfield.forms
from django.forms.models import ModelFormMetaclass
from django import forms
from django.core.files import File
from django.core.files.storage import default_storage
from django.core.files.uploadedfile import UploadedFile
from django.forms.models import (
BaseInlineFormSet, BaseModelForm, BaseModelFormSet, ModelFormMetaclass,
)
from django.utils import six
from django.utils.crypto import get_random_string
from hierarkey.forms import HierarkeyForm
from django.utils.translation import ugettext_lazy as _
from pretix.base.i18n import I18nFormField
from pretix.base.models import Event
from .validators import PlaceholderValidator # NOQA
logger = logging.getLogger('pretix.plugins.ticketoutputpdf')
class BaseI18nModelForm(i18nfield.forms.BaseI18nModelForm):
# compatibility shim for django-i18nfield library
class BaseI18nModelForm(BaseModelForm):
"""
This is a helperclass to construct an I18nModelForm.
"""
def __init__(self, *args, **kwargs):
event = kwargs.pop('event', None)
if event:
kwargs['locales'] = event.settings.get('locales')
super().__init__(*args, **kwargs)
if event:
for k, field in self.fields.items():
if isinstance(field, I18nFormField):
field.widget.enabled_langcodes = event.settings.get('locales')
class I18nModelForm(six.with_metaclass(ModelFormMetaclass, BaseI18nModelForm)):
"""
This is a modified version of Django's ModelForm which differs from ModelForm in
only one way: The constructor takes one additional optional argument ``event``
expecting an `Event` instance. If given, this instance is used to select
the visible languages in all I18nFormFields of the form. If not given, all languages
will be displayed.
"""
pass
class I18nFormSet(i18nfield.forms.I18nModelFormSet):
# compatibility shim for django-i18nfield library
class I18nFormSet(BaseModelFormSet):
"""
This is equivalent to a normal BaseModelFormset, but cares for the special needs
of I18nForms (see there for more information).
"""
def __init__(self, *args, **kwargs):
event = kwargs.pop('event', None)
if event:
kwargs['locales'] = event.settings.get('locales')
self.event = kwargs.pop('event', None)
super().__init__(*args, **kwargs)
def _construct_form(self, i, **kwargs):
kwargs['event'] = self.event
return super()._construct_form(i, **kwargs)
class I18nInlineFormSet(i18nfield.forms.I18nInlineFormSet):
# compatibility shim for django-i18nfield library
@property
def empty_form(self):
form = self.form(
auto_id=self.auto_id,
prefix=self.add_prefix('__prefix__'),
empty_permitted=True,
event=self.event
)
self.add_fields(form, None)
return form
class I18nInlineFormSet(BaseInlineFormSet):
"""
This is equivalent to a normal BaseInlineFormset, but cares for the special needs
of I18nForms (see there for more information).
"""
def __init__(self, *args, **kwargs):
event = kwargs.pop('event', None)
if event:
kwargs['locales'] = event.settings.get('locales')
self.event = kwargs.pop('event', None)
super().__init__(*args, **kwargs)
def _construct_form(self, i, **kwargs):
kwargs['event'] = self.event
return super()._construct_form(i, **kwargs)
class SettingsForm(i18nfield.forms.I18nFormMixin, HierarkeyForm):
class SettingsForm(forms.Form):
"""
This form is meant to be used for modifying EventSettings or OrganizerSettings. It takes
care of loading the current values of the fields and saving the field inputs to the
settings storage. It also deals with setting the available languages for internationalized
fields.
:param obj: The event or organizer object which should be used for the settings storage
"""
BOOL_CHOICES = (
('False', _('disabled')),
('True', _('enabled')),
)
def __init__(self, *args, **kwargs):
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
self.obj = kwargs.pop('obj')
kwargs['initial'] = self.obj.settings.freeze()
super().__init__(*args, **kwargs)
for k, field in self.fields.items():
if isinstance(field, I18nFormField):
field.widget.enabled_langcodes = self.obj.settings.get('locales')
def get_new_filename(self, name: str) -> str:
nonce = get_random_string(length=8)
if isinstance(self.obj, Event):
fname = '%s/%s/%s.%s.%s' % (
self.obj.organizer.slug, self.obj.slug, name, nonce, name.split('.')[-1]
)
else:
fname = '%s/%s.%s.%s' % (self.obj.slug, name, nonce, name.split('.')[-1])
return fname
def save(self):
"""
Performs the save operation
"""
for name, field in self.fields.items():
value = self.cleaned_data[name]
if isinstance(value, UploadedFile):
# Delete old file
fname = self.obj.settings.get(name, as_type=File)
if fname:
try:
default_storage.delete(fname.name)
except OSError:
logger.error('Deleting file %s failed.' % fname.name)
# Create new file
nonce = get_random_string(length=8)
if isinstance(self.obj, Event):
fname = '%s/%s/%s.%s.%s' % (
self.obj.organizer.slug, self.obj.slug, name, nonce, value.name.split('.')[-1]
)
else:
fname = '%s/%s.%s.%s' % (self.obj.slug, name, nonce, value.name.split('.')[-1])
newname = default_storage.save(fname, value)
value._name = newname
self.obj.settings.set(name, value)
elif isinstance(value, File):
# file is unchanged
continue
elif isinstance(field, forms.FileField):
# file is deleted
fname = self.obj.settings.get(name, as_type=File)
if fname:
try:
default_storage.delete(fname.name)
except OSError:
logger.error('Deleting file %s failed.' % fname.name)
del self.obj.settings[name]
elif value is None:
del self.obj.settings[name]
elif self.obj.settings.get(name, as_type=type(value)) != value:
self.obj.settings.set(name, value)

View File

@@ -39,7 +39,8 @@ class UserSettingsForm(forms.ModelForm):
class Meta:
model = User
fields = [
'fullname',
'givenname',
'familyname',
'locale',
# 'timezone',
'email'
@@ -104,7 +105,7 @@ class UserSettingsForm(forms.ModelForm):
class User2FADeviceAddForm(forms.Form):
name = forms.CharField(label=_('Device name'), max_length=64)
name = forms.CharField(label=_('Device name'))
devicetype = forms.ChoiceField(label=_('Device type'), widget=forms.RadioSelect, choices=(
('totp', _('Smartphone with the Authenticator application')),
('u2f', _('U2F-compatible hardware token (e.g. Yubikey)')),

View File

@@ -1,38 +0,0 @@
import re
from django.core.exceptions import ValidationError
from django.core.validators import BaseValidator
from django.utils.translation import ugettext_lazy as _
from i18nfield.strings import LazyI18nString
class PlaceholderValidator(BaseValidator):
"""
Takes list of allowed placeholders,
validates form field by checking for placeholders,
which are not presented in taken list.
"""
def __init__(self, limit_value):
super().__init__(limit_value)
self.limit_value = limit_value
def __call__(self, value):
if isinstance(value, LazyI18nString):
for l, v in value.data.items():
self.__call__(v)
return
data_placeholders = list(re.findall(r'({[\w\s]*})', value, re.X))
invalid_placeholders = []
for placeholder in data_placeholders:
if placeholder not in self.limit_value:
invalid_placeholders.append(placeholder)
if invalid_placeholders:
raise ValidationError(
_('Invalid placeholder(s): %(value)s'),
code='invalid',
params={'value': ", ".join(invalid_placeholders,)})
def clean(self, x):
return x

View File

@@ -1,16 +1,339 @@
import copy
import json
from contextlib import contextmanager
from typing import Dict, List, Optional, Union
from django import forms
from django.conf import settings
from django.core.serializers.json import DjangoJSONEncoder
from django.db.models import Model, QuerySet, TextField
from django.utils import translation
from django.utils.formats import date_format, number_format
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext
from i18nfield.fields import ( # noqa
I18nCharField, I18nTextarea, I18nTextField, I18nTextInput,
)
from i18nfield.forms import I18nFormField # noqa
# Compatibility imports
from i18nfield.strings import LazyI18nString # noqa
from i18nfield.utils import I18nJSONEncoder # noqa
class LazyI18nString:
"""
This represents an internationalized string that is/was/will be stored in the database.
"""
def __init__(self, data: Optional[Union[str, Dict[str, str]]]):
"""
Creates a new i18n-aware string.
:param data: If this is a dictionary, it is expected to map language codes to translations.
If this is a string that can be parsed as JSON, it will be parsed and used as such a dictionary.
If this is anything else, it will be cast to a string and used for all languages.
"""
self.data = data
if isinstance(self.data, str) and self.data is not None:
try:
j = json.loads(self.data)
except ValueError:
pass
else:
self.data = j
def __str__(self) -> str:
"""
Evaluate the given string with respect to the currently active locale.
If no string is available in the currently active language, this will give you
the string in the system's default language. If this is unavailable as well, it
will give you the string in the first language available.
"""
return self.localize(translation.get_language() or settings.LANGUAGE_CODE)
def __bool__(self):
if not self.data:
return False
if isinstance(self.data, dict):
return any(self.data.values())
return True
def localize(self, lng: str) -> str:
"""
Evaluate the given string with respect to the locale defined by ``lng``.
If no string is available in the currently active language, this will give you
the string in the system's default language. If this is unavailable as well, it
will give you the string in the first language available.
:param lng: A locale code, e.g. ``de``. If you specify a code including a country
or region like ``de-AT``, exact matches will be used preferably, but if only
a ``de`` or ``de-AT`` translation exists, this might be returned as well.
"""
if self.data is None:
return ""
if isinstance(self.data, dict):
firstpart = lng.split('-')[0]
similar = [l for l in self.data.keys() if l.startswith(firstpart + "-") or firstpart == l]
if lng in self.data and self.data[lng]:
return self.data[lng]
elif firstpart in self.data:
return self.data[firstpart]
elif similar:
return self.data[similar[0]]
elif settings.LANGUAGE_CODE in self.data and self.data[settings.LANGUAGE_CODE]:
return self.data[settings.LANGUAGE_CODE]
elif len(self.data):
return list(self.data.items())[0][1]
else:
return ""
else:
return str(self.data)
def __repr__(self) -> str: # NOQA
return '<LazyI18nString: %s>' % repr(self.data)
def __lt__(self, other) -> bool: # NOQA
return str(self) < str(other)
def __format__(self, format_spec):
return self.__str__()
def __eq__(self, other):
if other is None:
return False
if hasattr(other, 'data'):
return self.data == other.data
return self.data == other
class LazyGettextProxy:
def __init__(self, lazygettext):
self.lazygettext = lazygettext
def __getitem__(self, item):
with language(item):
return str(ugettext(self.lazygettext))
def __contains__(self, item):
return True
def __str__(self):
return str(ugettext(self.lazygettext))
@classmethod
def from_gettext(cls, lazygettext):
l = LazyI18nString({})
l.data = cls.LazyGettextProxy(lazygettext)
return l
class I18nWidget(forms.MultiWidget):
"""
The default form widget for I18nCharField and I18nTextField. It makes
use of Django's MultiWidget mechanism and does some magic to save you
time.
"""
widget = forms.TextInput
def __init__(self, langcodes: List[str], field: forms.Field, attrs=None):
widgets = []
self.langcodes = langcodes
self.enabled_langcodes = langcodes
self.field = field
for lng in self.langcodes:
a = copy.copy(attrs) or {}
a['lang'] = lng
widgets.append(self.widget(attrs=a))
super().__init__(widgets, attrs)
def decompress(self, value):
data = []
first_enabled = None
any_filled = False
if not isinstance(value, LazyI18nString):
value = LazyI18nString(value)
for i, lng in enumerate(self.langcodes):
dataline = (
value.data[lng]
if value is not None and (
isinstance(value.data, dict) or isinstance(value.data, LazyI18nString.LazyGettextProxy)
) and lng in value.data
else None
)
any_filled = any_filled or (lng in self.enabled_langcodes and dataline)
if not first_enabled and lng in self.enabled_langcodes:
first_enabled = i
data.append(dataline)
if value and not isinstance(value.data, dict):
data[first_enabled] = value.data
return data
def render(self, name, value, attrs=None):
if self.is_localized:
for widget in self.widgets:
widget.is_localized = self.is_localized
# value is a list of values, each corresponding to a widget
# in self.widgets.
if not isinstance(value, list):
value = self.decompress(value)
output = []
final_attrs = self.build_attrs(attrs)
id_ = final_attrs.get('id', None)
for i, widget in enumerate(self.widgets):
if self.langcodes[i] not in self.enabled_langcodes:
continue
try:
widget_value = value[i]
except IndexError:
widget_value = None
if id_:
final_attrs = dict(
final_attrs,
id='%s_%s' % (id_, i),
title=self.langcodes[i]
)
output.append(widget.render(name + '_%s' % i, widget_value, final_attrs))
return mark_safe(self.format_output(output))
def format_output(self, rendered_widgets):
return '<div class="i18n-form-group">%s</div>' % super().format_output(rendered_widgets)
class I18nTextInput(I18nWidget):
widget = forms.TextInput
class I18nTextarea(I18nWidget):
widget = forms.Textarea
class I18nFormField(forms.MultiValueField):
"""
The form field that is used by I18nCharField and I18nTextField. It makes use
of Django's MultiValueField mechanism to create one sub-field per available
language.
It contains special treatment to make sure that a field marked as "required" is validated
as "filled out correctly" if *at least one* translation is filled it. It is never required
to fill in all of them. This has the drawback that the HTML property ``required`` is set on
none of the fields as this would lead to irritating behaviour.
:param langcodes: An iterable of locale codes that the widget should render a field for. If
omitted, fields will be rendered for all languages supported by pretix.
"""
def compress(self, data_list):
langcodes = self.langcodes
data = {}
for i, value in enumerate(data_list):
data[langcodes[i]] = value
return LazyI18nString(data)
def clean(self, value):
if isinstance(value, LazyI18nString):
# This happens e.g. if the field is disabled
return value
found = False
clean_data = []
errors = []
for i, field in enumerate(self.fields):
try:
field_value = value[i]
except IndexError:
field_value = None
if field_value not in self.empty_values:
found = True
try:
clean_data.append(field.clean(field_value))
except forms.ValidationError as e:
# Collect all validation errors in a single list, which we'll
# raise at the end of clean(), rather than raising a single
# exception for the first error we encounter. Skip duplicates.
errors.extend(m for m in e.error_list if m not in errors)
if errors:
raise forms.ValidationError(errors)
if self.one_required and not found:
raise forms.ValidationError(self.error_messages['required'], code='required')
out = self.compress(clean_data)
self.validate(out)
self.run_validators(out)
return out
def __init__(self, *args, **kwargs):
fields = []
defaults = {
'widget': self.widget,
'max_length': kwargs.pop('max_length', None),
}
self.langcodes = kwargs.pop('langcodes', [l[0] for l in settings.LANGUAGES])
self.one_required = kwargs.get('required', True)
kwargs['required'] = False
kwargs['widget'] = kwargs['widget'](
langcodes=self.langcodes, field=self, **kwargs.pop('widget_kwargs', {})
)
defaults.update(**kwargs)
for lngcode in self.langcodes:
defaults['label'] = '%s (%s)' % (defaults.get('label'), lngcode)
fields.append(forms.CharField(**defaults))
super().__init__(
fields=fields, require_all_fields=False, *args, **kwargs
)
class I18nFieldMixin:
form_class = I18nFormField
widget = I18nTextInput
def __init__(self, *args, **kwargs):
self.event = kwargs.pop('event', None)
super().__init__(*args, **kwargs)
def to_python(self, value):
if isinstance(value, LazyI18nString):
return value
return LazyI18nString(value)
def get_prep_value(self, value):
if isinstance(value, LazyI18nString):
value = value.data
if isinstance(value, dict):
return json.dumps({k: v for k, v in value.items() if v}, sort_keys=True)
return value
def get_prep_lookup(self, lookup_type, value): # NOQA
raise TypeError('Lookups on i18n string currently not supported.')
def from_db_value(self, value, expression, connection, context):
return LazyI18nString(value)
def formfield(self, **kwargs):
defaults = {'form_class': self.form_class, 'widget': self.widget}
defaults.update(kwargs)
return super().formfield(**defaults)
class I18nCharField(I18nFieldMixin, TextField):
"""
A CharField which takes internationalized data. Internally, a TextField dabase
field is used to store JSON. If you interact with this field, you will work
with LazyI18nString instances.
"""
widget = I18nTextInput
class I18nTextField(I18nFieldMixin, TextField):
"""
Like I18nCharField, but for TextFields.
"""
widget = I18nTextarea
class I18nJSONEncoder(DjangoJSONEncoder):
def default(self, obj):
if isinstance(obj, LazyI18nString):
return obj.data
elif isinstance(obj, QuerySet):
return list(obj)
elif isinstance(obj, Model):
return {'type': obj.__class__.__name__, 'id': obj.id}
else:
return super().default(obj)
class LazyDate:
@@ -47,11 +370,10 @@ def language(lng):
class LazyLocaleException(Exception):
def __init__(self, *args):
self.msg = args[0]
self.msgargs = args[1] if len(args) > 1 else None
self.args = args
super().__init__(self.msg, self.msgargs)
def __init__(self, msg, msgargs=None):
self.msg = msg
self.msgargs = msgargs
super().__init__(msg, msgargs)
def __str__(self):
if self.msgargs:

View File

@@ -1,23 +0,0 @@
from django.core.management import call_command
from django.core.management.base import BaseCommand
from pretix.base.settings import GlobalSettingsObject
class Command(BaseCommand):
help = "Rebuild static files and language files"
def handle(self, *args, **options):
call_command('compilemessages', verbosity=1, interactive=False)
call_command('compilejsi18n', verbosity=1, interactive=False)
call_command('collectstatic', verbosity=1, interactive=False)
call_command('compress', verbosity=1, interactive=False)
try:
gs = GlobalSettingsObject()
del gs.settings.update_check_last
del gs.settings.update_check_result
del gs.settings.update_check_result_warning
except:
# Fails when this is executed without a valid database configuration.
# We don't care.
pass

View File

@@ -1,28 +1,10 @@
import math
from collections import defaultdict
from django.apps import apps
from django.conf import settings
if settings.HAS_REDIS:
import django_redis
redis = django_redis.get_redis_connection("redis")
REDIS_KEY = "pretix_metrics"
_INF = float("inf")
_MINUS_INF = float("-inf")
def _float_to_go_string(d):
# inspired by https://github.com/prometheus/client_python/blob/master/prometheus_client/core.py
if d == _INF:
return '+Inf'
elif d == _MINUS_INF:
return '-Inf'
elif math.isnan(d):
return 'NaN'
else:
return repr(float(d))
REDIS_KEY_PREFIX = "pretix_metrics_"
class Metric(object):
@@ -52,7 +34,7 @@ class Metric(object):
if len(labels) != len(self.labelnames):
raise ValueError("Unknown labels used: {}".format(", ".join(set(labels) - set(self.labelnames))))
def _construct_metric_identifier(self, metricname, labels=None, labelnames=None):
def _construct_metric_identifier(self, metricname, labels=None):
"""
Constructs the scrapable metricname usable in the output format.
"""
@@ -60,36 +42,26 @@ class Metric(object):
return metricname
else:
named_labels = []
for labelname in (labelnames or self.labelnames):
named_labels.append('{}="{}"'.format(labelname, labels[labelname]))
for labelname in self.labelnames:
named_labels.append('{}="{}",'.format(labelname, labels[labelname]))
return metricname + "{" + ",".join(named_labels) + "}"
def _inc_in_redis(self, key, amount, pipeline=None):
def _inc_in_redis(self, key, amount):
"""
Increments given key in Redis.
"""
rkey = REDIS_KEY_PREFIX + key
if settings.HAS_REDIS:
if not pipeline:
pipeline = redis
pipeline.hincrbyfloat(REDIS_KEY, key, amount)
redis.incrbyfloat(rkey, amount)
def _set_in_redis(self, key, value, pipeline=None):
def _set_in_redis(self, key, value):
"""
Sets given key in Redis.
"""
rkey = REDIS_KEY_PREFIX + key
if settings.HAS_REDIS:
if not pipeline:
pipeline = redis
pipeline.hset(REDIS_KEY, key, value)
def _get_redis_pipeline(self):
if settings.HAS_REDIS:
return redis.pipeline()
def _execute_redis_pipeline(self, pipeline):
if settings.HAS_REDIS:
return pipeline.execute()
redis.set(rkey, value)
class Counter(Metric):
@@ -152,79 +124,21 @@ class Gauge(Metric):
self._inc_in_redis(fullmetric, amount * -1)
class Histogram(Metric):
"""
Histogram Metric Object
"""
def __init__(self, name, helpstring, labelnames=None,
buckets=(.005, .01, .025, .05, .075, .1, .25, .5, .75, 1.0, 2.5, 5.0, 7.5, 10.0, 30.0, _INF)):
if list(buckets) != sorted(buckets):
# This is probably an error on the part of the user,
# so raise rather than sorting for them.
raise ValueError('Buckets not in sorted order')
if buckets and buckets[-1] != _INF:
buckets.append(_INF)
if len(buckets) < 2:
raise ValueError('Must have at least two buckets')
self.buckets = buckets
super().__init__(name, helpstring, labelnames)
def observe(self, amount, **kwargs):
"""
Stores a value in the histogram for the labels specified in kwargs.
"""
if amount < 0:
raise ValueError("Amount must be greater than zero. Otherwise use inc().")
self._check_label_consistency(kwargs)
pipe = self._get_redis_pipeline()
countmetric = self._construct_metric_identifier(self.name + '_count', kwargs)
self._inc_in_redis(countmetric, 1, pipeline=pipe)
summetric = self._construct_metric_identifier(self.name + '_sum', kwargs)
self._inc_in_redis(summetric, amount, pipeline=pipe)
kwargs_le = dict(kwargs.items())
for i, bound in enumerate(self.buckets):
if amount <= bound:
kwargs_le['le'] = _float_to_go_string(bound)
bmetric = self._construct_metric_identifier(self.name + '_bucket', kwargs_le,
labelnames=self.labelnames + ["le"])
self._inc_in_redis(bmetric, 1, pipeline=pipe)
self._execute_redis_pipeline(pipe)
def metric_values():
"""
Produces the the values to be presented to the monitoring system
Produces the scrapable textformat to be presented to the monitoring system
"""
metrics = defaultdict(dict)
if not settings.HAS_REDIS:
return ""
# Metrics from redis
if settings.HAS_REDIS:
for key, value in redis.hscan_iter(REDIS_KEY):
dkey = key.decode("utf-8")
splitted = dkey.split("{", 2)
value = float(value.decode("utf-8"))
metrics[splitted[0]]["{" + splitted[1]] = value
metrics = {}
# Aliases
aliases = {
'pretix_view_requests_total': 'pretix_view_duration_seconds_count'
}
for a, atarget in aliases.items():
metrics[a] = metrics[atarget]
for key in redis.scan_iter(match=REDIS_KEY_PREFIX + "*"):
dkey = key.decode("utf-8")
_, _, output_key = dkey.split("_", 2)
value = float(redis.get(dkey).decode("utf-8"))
# Throwaway metrics
for m in apps.get_models(): # Count all models
metrics['pretix_model_instances']['{model="%s"}' % m._meta] = m.objects.count()
metrics[output_key] = value
return metrics
@@ -232,9 +146,5 @@ def metric_values():
"""
Provided metrics
"""
pretix_view_duration_seconds = Histogram("pretix_view_duration_seconds", "Return time of views.",
["status_code", "method", "url_name"])
pretix_task_runs_total = Counter("pretix_task_runs_total", "Total calls to a celery task",
["task_name", "status"])
pretix_task_duration_seconds = Histogram("pretix_task_duration_seconds", "Call time of a celery task",
["task_name"])
http_requests_total = Counter("http_requests_total", "Total number of HTTP requests made.", ["code", "handler", "method"])
# usage: http_requests_total.inc(code="200", handler="/foo", method="GET")

View File

@@ -135,30 +135,18 @@ def get_language_from_request(request: HttpRequest) -> str:
)
def _parse_csp(header):
h = {}
for part in header.split(';'):
k, v = part.strip().split(' ', 1)
h[k.strip()] = v.split(' ')
return h
def _render_csp(h):
return "; ".join(k + ' ' + ' '.join(v) for k, v in h.items())
def _merge_csp(a, b):
for k, v in a.items():
if k in b:
a[k] += b[k]
for k, v in b.items():
if k not in a:
a[k] = b[k]
class SecurityMiddleware(MiddlewareMixin):
def _parse_csp(self, header):
h = {}
for part in header.split(';'):
k, v = part.strip().split(' ', 1)
h[k.strip()] = v
return h
def _render_csp(self, h):
return "; ".join(k + ' ' + v for k, v in h.items())
def process_response(self, request, resp):
if settings.DEBUG and resp.status_code >= 400:
# Don't use CSP on debug error page as it breaks of Django's fancy error
@@ -167,23 +155,23 @@ class SecurityMiddleware(MiddlewareMixin):
resp['X-XSS-Protection'] = '1'
h = {
'default-src': ["{static}"],
'script-src': ['{static}', 'https://checkout.stripe.com', 'https://js.stripe.com'],
'object-src': ["'none'"],
'default-src': "{static}",
'script-src': '{static} https://checkout.stripe.com https://js.stripe.com',
'object-src': "'none'",
# frame-src is deprecated but kept for compatibility with CSP 1.0 browsers, e.g. Safari 9
'frame-src': ['{static}', 'https://checkout.stripe.com', 'https://js.stripe.com'],
'child-src': ['{static}', 'https://checkout.stripe.com', 'https://js.stripe.com'],
'style-src': ["{static}"],
'connect-src': ["{dynamic}", "https://checkout.stripe.com"],
'img-src': ["{static}", "data:", "https://*.stripe.com"],
'frame-src': '{static} https://checkout.stripe.com https://js.stripe.com',
'child-src': '{static} https://checkout.stripe.com https://js.stripe.com',
'style-src': "{static}",
'connect-src': "{dynamic} https://checkout.stripe.com",
'img-src': "{static} data: https://*.stripe.com",
# form-action is not only used to match on form actions, but also on URLs
# form-actions redirect to. In the context of e.g. payment providers or
# single-sign-on this can be nearly anything so we cannot really restrict
# this. However, we'll restrict it to HTTPS.
'form-action': ["{dynamic}", "https:"],
'form-action': "{dynamic} https:",
}
if 'Content-Security-Policy' in resp:
_merge_csp(h, _parse_csp(resp['Content-Security-Policy']))
h.update(self._parse_csp(resp['Content-Security-Policy']))
staticdomain = "'self'"
dynamicdomain = "'self'"
@@ -196,5 +184,5 @@ class SecurityMiddleware(MiddlewareMixin):
else:
staticdomain += " " + settings.SITE_URL
dynamicdomain += " " + settings.SITE_URL
resp['Content-Security-Policy'] = _render_csp(h).format(static=staticdomain, dynamic=dynamicdomain)
resp['Content-Security-Policy'] = self._render_csp(h).format(static=staticdomain, dynamic=dynamicdomain)
return resp

View File

@@ -1,658 +0,0 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-02-03 14:20
from __future__ import unicode_literals
import datetime
import uuid
from decimal import Decimal
import django.core.validators
import django.db.models.deletion
import i18nfield.fields
from django.conf import settings
from django.contrib.auth.hashers import make_password
from django.db import migrations, models
import pretix.base.models.base
import pretix.base.models.invoices
import pretix.base.models.items
import pretix.base.models.orders
import pretix.base.models.vouchers
def initial_user(apps, schema_editor):
User = apps.get_model("pretixbase", "User")
user = User(email='admin@localhost')
user.is_staff = True
user.is_superuser = True
user.password = make_password('admin')
user.save()
class Migration(migrations.Migration):
replaces = [('pretixbase', '0001_initial'), ('pretixbase', '0002_auto_20160209_0940'), ('pretixbase', '0003_eventpermission_can_change_vouchers'), ('pretixbase', '0004_auto_20160209_1023'), ('pretixbase', '0005_auto_20160211_1459'), ('pretixbase', '0006_auto_20160211_1630'), ('pretixbase', '0007_auto_20160211_1710'), ('pretixbase', '0008_invoiceaddress'), ('pretixbase', '0009_auto_20160222_2002'), ('pretixbase', '0010_orderposition_secret'), ('pretixbase', '0011_auto_20160311_2052'), ('pretixbase', '0012_auto_20160312_1040'), ('pretixbase', '0013_invoice_locale'), ('pretixbase', '0014_invoice_additional_text'), ('pretixbase', '0015_auto_20160312_1924'), ('pretixbase', '0016_voucher_variation'), ('pretixbase', '0017_auto_20160324_1615'), ('pretixbase', '0018_auto_20160326_1104'), ('pretixbase', '0019_auto_20160326_1139'), ('pretixbase', '0020_auto_20160418_2106'), ('pretixbase', '0021_auto_20160418_2117'), ('pretixbase', '0020_auto_20160421_1943'), ('pretixbase', '0022_merge'), ('pretixbase', '0023_auto_20160601_1039'), ('pretixbase', '0024_auto_20160728_1725'), ('pretixbase', '0025_auto_20160802_2202'), ('pretixbase', '0026_order_comment'), ('pretixbase', '0027_auto_20160815_1254'), ('pretixbase', '0028_auto_20160816_1242')]
initial = True
dependencies = [
('auth', '0006_require_contenttypes_0002'),
('contenttypes', '0002_remove_content_type_name'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('email', models.EmailField(blank=True, db_index=True, max_length=254, null=True, unique=True, verbose_name='E-mail')),
('givenname', models.CharField(blank=True, max_length=255, null=True, verbose_name='Given name')),
('familyname', models.CharField(blank=True, max_length=255, null=True, verbose_name='Family name')),
('is_active', models.BooleanField(default=True, verbose_name='Is active')),
('is_staff', models.BooleanField(default=False, verbose_name='Is site admin')),
('date_joined', models.DateTimeField(auto_now_add=True, verbose_name='Date joined')),
('locale', models.CharField(choices=[('en', 'English'), ('de', 'German'), ('de-informal', 'German (informal)')], default='en', max_length=50, verbose_name='Language')),
('timezone', models.CharField(default='UTC', max_length=100, verbose_name='Timezone')),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'verbose_name': 'User',
'verbose_name_plural': 'Users',
},
),
migrations.RunPython(
code=initial_user,
),
migrations.CreateModel(
name='CachedFile',
fields=[
('id', models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False)),
('expires', models.DateTimeField(blank=True, null=True)),
('date', models.DateTimeField(blank=True, null=True)),
('filename', models.CharField(max_length=255)),
('type', models.CharField(max_length=255)),
('file', models.FileField(blank=True, null=True, upload_to=pretix.base.models.base.cachedfile_name)),
],
),
migrations.CreateModel(
name='CachedTicket',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('provider', models.CharField(max_length=255)),
('cachedfile', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='pretixbase.CachedFile')),
],
),
migrations.CreateModel(
name='CartPosition',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('price', models.DecimalField(decimal_places=2, max_digits=10, verbose_name='Price')),
('attendee_name', models.CharField(blank=True, help_text='Empty, if this product is not an admission ticket', max_length=255, null=True, verbose_name='Attendee name')),
('voucher_discount', models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=10)),
('base_price', models.DecimalField(blank=True, decimal_places=2, max_digits=10, null=True)),
('cart_id', models.CharField(blank=True, max_length=255, null=True, verbose_name='Cart ID (e.g. session key)')),
('datetime', models.DateTimeField(auto_now_add=True, verbose_name='Date')),
('expires', models.DateTimeField(verbose_name='Expiration date')),
],
options={
'verbose_name': 'Cart position',
'verbose_name_plural': 'Cart positions',
},
),
migrations.CreateModel(
name='Event',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', i18nfield.fields.I18nCharField(max_length=200, verbose_name='Name')),
('slug', models.SlugField(help_text='Should be short, only contain lowercase letters and numbers, and must be unique among your events. This is being used in addresses and bank transfer references.', validators=[django.core.validators.RegexValidator(message='The slug may only contain letters, numbers, dots and dashes.', regex='^[a-zA-Z0-9.-]+$')], verbose_name='Slug')),
('currency', models.CharField(default='EUR', max_length=10, verbose_name='Default currency')),
('date_from', models.DateTimeField(verbose_name='Event start time')),
('date_to', models.DateTimeField(blank=True, null=True, verbose_name='Event end time')),
('is_public', models.BooleanField(default=False, help_text="If selected, this event may show up on the ticket system's start page or an organization profile.", verbose_name='Visible in public lists')),
('presale_end', models.DateTimeField(blank=True, help_text='No products will be sold after this date.', null=True, verbose_name='End of presale')),
('presale_start', models.DateTimeField(blank=True, help_text='No products will be sold before this date.', null=True, verbose_name='Start of presale')),
('plugins', models.TextField(blank=True, null=True, verbose_name='Plugins')),
],
options={
'verbose_name': 'Event',
'ordering': ('date_from', 'name'),
'verbose_name_plural': 'Events',
},
bases=(models.Model, pretix.base.models.base.LoggingMixin),
),
migrations.CreateModel(
name='EventLock',
fields=[
('event', models.CharField(max_length=36, primary_key=True, serialize=False)),
('date', models.DateTimeField(auto_now=True)),
('token', models.UUIDField(default=uuid.uuid4)),
],
),
migrations.CreateModel(
name='EventPermission',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('can_change_settings', models.BooleanField(default=True, verbose_name='Can change event settings')),
('can_change_items', models.BooleanField(default=True, verbose_name='Can change product settings')),
('can_view_orders', models.BooleanField(default=True, verbose_name='Can view orders')),
('can_change_permissions', models.BooleanField(default=True, verbose_name='Can change permissions')),
('can_change_orders', models.BooleanField(default=True, verbose_name='Can change orders')),
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_perms', to='pretixbase.Event')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='event_perms', to=settings.AUTH_USER_MODEL)),
('can_change_vouchers', models.BooleanField(default=True, verbose_name='Can change vouchers')),
],
options={
'verbose_name': 'Event permission',
'verbose_name_plural': 'Event permissions',
},
),
migrations.CreateModel(
name='EventSetting',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('key', models.CharField(max_length=255)),
('value', models.TextField()),
('object', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='setting_objects', to='pretixbase.Event')),
],
),
migrations.CreateModel(
name='Item',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', i18nfield.fields.I18nCharField(max_length=255, verbose_name='Item name')),
('active', models.BooleanField(default=True, verbose_name='Active')),
('description', i18nfield.fields.I18nTextField(blank=True, help_text='This is shown below the product name in lists.', null=True, verbose_name='Description')),
('default_price', models.DecimalField(decimal_places=2, max_digits=7, null=True, verbose_name='Default price')),
('tax_rate', models.DecimalField(blank=True, decimal_places=2, max_digits=7, null=True, verbose_name='Taxes included in percent')),
('admission', models.BooleanField(default=False, help_text='Whether or not buying this product allows a person to enter your event', verbose_name='Is an admission ticket')),
('position', models.IntegerField(default=0)),
('picture', models.ImageField(blank=True, null=True, upload_to=pretix.base.models.items.itempicture_upload_to, verbose_name='Product picture')),
('available_from', models.DateTimeField(blank=True, help_text='This product will not be sold before the given date.', null=True, verbose_name='Available from')),
('available_until', models.DateTimeField(blank=True, help_text='This product will not be sold after the given date.', null=True, verbose_name='Available until')),
],
options={
'verbose_name': 'Product',
'ordering': ('category__position', 'category', 'position'),
'verbose_name_plural': 'Products',
},
bases=(models.Model, pretix.base.models.base.LoggingMixin),
),
migrations.CreateModel(
name='ItemCategory',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', i18nfield.fields.I18nCharField(max_length=255, verbose_name='Category name')),
('position', models.IntegerField(default=0)),
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='categories', to='pretixbase.Event')),
('description', i18nfield.fields.I18nTextField(blank=True, verbose_name='Category description')),
],
options={
'verbose_name': 'Product category',
'ordering': ('position', 'id'),
'verbose_name_plural': 'Product categories',
},
bases=(models.Model, pretix.base.models.base.LoggingMixin),
),
migrations.CreateModel(
name='ItemVariation',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('value', i18nfield.fields.I18nCharField(max_length=255, verbose_name='Description')),
('active', models.BooleanField(default=True, verbose_name='Active')),
('position', models.PositiveIntegerField(default=0, verbose_name='Position')),
('default_price', models.DecimalField(blank=True, decimal_places=2, max_digits=7, null=True, verbose_name='Default price')),
('item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='variations', to='pretixbase.Item')),
],
options={
'verbose_name': 'Product variation',
'ordering': ('position', 'id'),
'verbose_name_plural': 'Product variations',
},
),
migrations.CreateModel(
name='LogEntry',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('object_id', models.PositiveIntegerField()),
('datetime', models.DateTimeField(auto_now_add=True)),
('action_type', models.CharField(max_length=255)),
('data', models.TextField(default='{}')),
('content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')),
('event', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='pretixbase.Event')),
('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Order',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('code', models.CharField(max_length=16, verbose_name='Order code')),
('status', models.CharField(choices=[('n', 'pending'), ('p', 'paid'), ('e', 'expired'), ('c', 'cancelled'), ('r', 'refunded')], max_length=3, verbose_name='Status')),
('email', models.EmailField(blank=True, max_length=254, null=True, verbose_name='E-mail')),
('locale', models.CharField(blank=True, max_length=32, null=True, verbose_name='Locale')),
('secret', models.CharField(default=pretix.base.models.orders.generate_secret, max_length=32)),
('datetime', models.DateTimeField(verbose_name='Date')),
('expires', models.DateTimeField(verbose_name='Expiration date')),
('payment_date', models.DateTimeField(blank=True, null=True, verbose_name='Payment date')),
('payment_provider', models.CharField(blank=True, max_length=255, null=True, verbose_name='Payment provider')),
('payment_fee', models.DecimalField(decimal_places=2, default=0, max_digits=10, verbose_name='Payment method fee')),
('payment_info', models.TextField(blank=True, null=True, verbose_name='Payment information')),
('payment_manual', models.BooleanField(default=False, verbose_name='Payment state was manually modified')),
('total', models.DecimalField(decimal_places=2, max_digits=10, verbose_name='Total amount')),
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='orders', to='pretixbase.Event', verbose_name='Event')),
],
options={
'verbose_name': 'Order',
'ordering': ('-datetime',),
'verbose_name_plural': 'Orders',
},
bases=(models.Model, pretix.base.models.base.LoggingMixin),
),
migrations.CreateModel(
name='OrderPosition',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('price', models.DecimalField(decimal_places=2, max_digits=10, verbose_name='Price')),
('attendee_name', models.CharField(blank=True, help_text='Empty, if this product is not an admission ticket', max_length=255, null=True, verbose_name='Attendee name')),
('voucher_discount', models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=10)),
('base_price', models.DecimalField(blank=True, decimal_places=2, max_digits=10, null=True)),
('item', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='pretixbase.Item', verbose_name='Item')),
('order', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='positions', to='pretixbase.Order', verbose_name='Order')),
('variation', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='pretixbase.ItemVariation', verbose_name='Variation')),
],
options={
'verbose_name': 'Order position',
'verbose_name_plural': 'Order positions',
},
),
migrations.CreateModel(
name='Organizer',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=200, verbose_name='Name')),
('slug', models.SlugField(help_text='Should be short, only contain lowercase letters and numbers, and must be unique among your events. This is being used in addresses and bank transfer references.', validators=[django.core.validators.RegexValidator(message='The slug may only contain letters, numbers, dots and dashes.', regex='^[a-zA-Z0-9.-]+$')], verbose_name='Slug')),
],
options={
'verbose_name': 'Organizer',
'ordering': ('name',),
'verbose_name_plural': 'Organizers',
},
bases=(models.Model, pretix.base.models.base.LoggingMixin),
),
migrations.CreateModel(
name='OrganizerPermission',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('can_create_events', models.BooleanField(default=True, verbose_name='Can create events')),
('organizer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_perms', to='pretixbase.Organizer')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='organizer_perms', to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name': 'Organizer permission',
'verbose_name_plural': 'Organizer permissions',
},
),
migrations.CreateModel(
name='OrganizerSetting',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('key', models.CharField(max_length=255)),
('value', models.TextField()),
('object', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='setting_objects', to='pretixbase.Organizer')),
],
),
migrations.CreateModel(
name='Question',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('question', i18nfield.fields.I18nTextField(verbose_name='Question')),
('type', models.CharField(choices=[('N', 'Number'), ('S', 'Text (one line)'), ('T', 'Multiline text'), ('B', 'Yes/No')], max_length=5, verbose_name='Question type')),
('required', models.BooleanField(default=False, verbose_name='Required question')),
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='questions', to='pretixbase.Event')),
('items', models.ManyToManyField(blank=True, help_text='This question will be asked to buyers of the selected products', related_name='questions', to='pretixbase.Item', verbose_name='Products')),
],
options={
'verbose_name': 'Question',
'verbose_name_plural': 'Questions',
},
bases=(models.Model, pretix.base.models.base.LoggingMixin),
),
migrations.CreateModel(
name='QuestionAnswer',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('answer', models.TextField()),
('cartposition', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='answers', to='pretixbase.CartPosition')),
('orderposition', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='answers', to='pretixbase.OrderPosition')),
('question', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='answers', to='pretixbase.Question')),
],
),
migrations.CreateModel(
name='Quota',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=200, verbose_name='Name')),
('size', models.PositiveIntegerField(blank=True, help_text='Leave empty for an unlimited number of tickets.', null=True, verbose_name='Total capacity')),
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='quotas', to='pretixbase.Event', verbose_name='Event')),
('items', models.ManyToManyField(blank=True, related_name='quotas', to='pretixbase.Item', verbose_name='Item')),
('variations', models.ManyToManyField(blank=True, related_name='quotas', to='pretixbase.ItemVariation', verbose_name='Variations')),
],
options={
'verbose_name': 'Quota',
'verbose_name_plural': 'Quotas',
},
bases=(models.Model, pretix.base.models.base.LoggingMixin),
),
migrations.CreateModel(
name='Voucher',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('code', models.CharField(max_length=255, verbose_name='Voucher code')),
('valid_until', models.DateTimeField(blank=True, null=True, verbose_name='Valid until')),
('block_quota', models.BooleanField(default=False, help_text="If activated, this voucher will be substracted from the affected product's quotas, such that it is guaranteed that anyone with this voucher code does receive a ticket.", verbose_name='Reserve ticket from quota')),
('allow_ignore_quota', models.BooleanField(default=False, help_text='If activated, a holder of this voucher code can buy tickets, even if there are none left.', verbose_name='Allow to bypass quota')),
('price', models.DecimalField(blank=True, decimal_places=2, max_digits=10, null=True, verbose_name='Set product price to')),
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='vouchers', to='pretixbase.Event', verbose_name='Event')),
],
options={
'verbose_name': 'Voucher',
'verbose_name_plural': 'Vouchers',
},
),
migrations.AddField(
model_name='organizer',
name='permitted',
field=models.ManyToManyField(related_name='organizers', through='pretixbase.OrganizerPermission', to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='orderposition',
name='voucher',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='pretixbase.Voucher'),
),
migrations.AddField(
model_name='item',
name='category',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='items', to='pretixbase.ItemCategory', verbose_name='Category'),
),
migrations.AddField(
model_name='item',
name='event',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='items', to='pretixbase.Event', verbose_name='Event'),
),
migrations.AddField(
model_name='event',
name='organizer',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='events', to='pretixbase.Organizer'),
),
migrations.AddField(
model_name='event',
name='permitted',
field=models.ManyToManyField(related_name='events', through='pretixbase.EventPermission', to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='cartposition',
name='event',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='pretixbase.Event', verbose_name='Event'),
),
migrations.AddField(
model_name='cartposition',
name='item',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='pretixbase.Item', verbose_name='Item'),
),
migrations.AddField(
model_name='cartposition',
name='variation',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='pretixbase.ItemVariation', verbose_name='Variation'),
),
migrations.AddField(
model_name='cartposition',
name='voucher',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='pretixbase.Voucher'),
),
migrations.AddField(
model_name='cachedticket',
name='order',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='pretixbase.Order'),
),
migrations.AddField(
model_name='voucher',
name='item',
field=models.ForeignKey(blank=True, help_text="This product is added to the user's cart if the voucher is redeemed.", null=True, on_delete=django.db.models.deletion.CASCADE, related_name='vouchers', to='pretixbase.Item', verbose_name='Product'),
),
migrations.AlterField(
model_name='voucher',
name='price',
field=models.DecimalField(blank=True, decimal_places=2, help_text='If empty, the product will cost its normal price.', max_digits=10, null=True, verbose_name='Set product price to'),
),
migrations.AddField(
model_name='voucher',
name='redeemed',
field=models.BooleanField(default=False, verbose_name='Redeemed'),
),
migrations.AlterUniqueTogether(
name='voucher',
unique_together=set([('event', 'code')]),
),
migrations.AlterField(
model_name='voucher',
name='code',
field=models.CharField(default=pretix.base.models.vouchers.generate_code, max_length=255, verbose_name='Voucher code'),
),
migrations.AddField(
model_name='orderposition',
name='tax_rate',
field=models.DecimalField(decimal_places=2, default=0, max_digits=7, verbose_name='Tax rate'),
preserve_default=False,
),
migrations.AddField(
model_name='orderposition',
name='tax_value',
field=models.DecimalField(decimal_places=2, default=0, max_digits=10, verbose_name='Tax value'),
preserve_default=False,
),
migrations.AlterField(
model_name='item',
name='tax_rate',
field=models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=7, verbose_name='Taxes included in percent'),
),
migrations.CreateModel(
name='InvoiceAddress',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('last_modified', models.DateTimeField(auto_now=True)),
('company', models.CharField(blank=True, max_length=255, verbose_name='Company name')),
('name', models.CharField(blank=True, max_length=255, verbose_name='Full name')),
('street', models.TextField(verbose_name='Address')),
('zipcode', models.CharField(max_length=30, verbose_name='ZIP code')),
('city', models.CharField(max_length=255, verbose_name='City')),
('country', models.CharField(max_length=255, verbose_name='Country')),
('vat_id', models.CharField(blank=True, max_length=255, verbose_name='VAT ID')),
('order', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='invoice_address', to='pretixbase.Order')),
],
),
migrations.AddField(
model_name='event',
name='live',
field=models.BooleanField(default=False, verbose_name='Shop is live'),
),
migrations.AddField(
model_name='orderposition',
name='secret',
field=models.CharField(db_index=True, default=pretix.base.models.orders.generate_position_secret, max_length=64),
),
migrations.AddField(
model_name='order',
name='payment_fee_tax_rate',
field=models.DecimalField(decimal_places=2, default=0, max_digits=10, verbose_name='Payment method fee tax rate'),
preserve_default=False,
),
migrations.AddField(
model_name='order',
name='payment_fee_tax_value',
field=models.DecimalField(decimal_places=2, default=0, max_digits=10, verbose_name='Payment method fee tax'),
),
migrations.CreateModel(
name='Invoice',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('invoice_no', models.PositiveIntegerField(db_index=True)),
('is_cancelled', models.BooleanField(default=False)),
('invoice_from', models.TextField()),
('invoice_to', models.TextField()),
('date', models.DateField(default=datetime.date.today)),
('file', models.FileField(blank=True, null=True, upload_to=pretix.base.models.invoices.invoice_filename)),
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='invoices', to='pretixbase.Event')),
('order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='invoices', to='pretixbase.Order')),
],
),
migrations.CreateModel(
name='InvoiceLine',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('description', models.TextField()),
('gross_value', models.DecimalField(decimal_places=2, max_digits=10)),
('tax_value', models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=10)),
('tax_rate', models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=7)),
('invoice', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='lines', to='pretixbase.Invoice')),
],
),
migrations.AddField(
model_name='invoice',
name='locale',
field=models.CharField(default='en', max_length=50),
),
migrations.AddField(
model_name='invoice',
name='additional_text',
field=models.TextField(blank=True),
),
migrations.RemoveField(
model_name='invoice',
name='is_cancelled',
),
migrations.AddField(
model_name='invoice',
name='is_cancellation',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='invoice',
name='refers',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='refered', to='pretixbase.Invoice'),
),
migrations.AlterUniqueTogether(
name='invoice',
unique_together=set([('event', 'invoice_no')]),
),
migrations.AddField(
model_name='voucher',
name='variation',
field=models.ForeignKey(blank=True, help_text='This variation of the product select above is being used.', null=True, on_delete=django.db.models.deletion.CASCADE, related_name='vouchers', to='pretixbase.ItemVariation', verbose_name='Product variation'),
),
migrations.AlterModelOptions(
name='logentry',
options={'ordering': ('-datetime',)},
),
migrations.AddField(
model_name='item',
name='free_price',
field=models.BooleanField(default=False, help_text='If this option is active, your users can choose the price themselves. The price configured above is then interpreted as the minimum price a user has to enter. You could use this e.g. to collect additional donations for your event.', verbose_name='Free price input'),
),
migrations.CreateModel(
name='QuestionOption',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('answer', i18nfield.fields.I18nCharField(verbose_name='Answer')),
],
),
migrations.AlterField(
model_name='question',
name='type',
field=models.CharField(choices=[('N', 'Number'), ('S', 'Text (one line)'), ('T', 'Multiline text'), ('B', 'Yes/No'), ('C', 'Choose one from a list'), ('M', 'Choose multiple from a list')], max_length=5, verbose_name='Question type'),
),
migrations.AddField(
model_name='questionoption',
name='question',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='options', to='pretixbase.Question'),
),
migrations.AddField(
model_name='questionanswer',
name='options',
field=models.ManyToManyField(blank=True, related_name='answers', to='pretixbase.QuestionOption'),
),
migrations.AddField(
model_name='voucher',
name='quota',
field=models.ForeignKey(blank=True, help_text='If enabled, the voucher is valid for any product affected by this quota.', null=True, on_delete=django.db.models.deletion.CASCADE, related_name='quota', to='pretixbase.Quota', verbose_name='Quota'),
),
migrations.AddField(
model_name='voucher',
name='comment',
field=models.TextField(blank=True, help_text='The text entered in this field will not be visible to the user and is available for your convenience.', verbose_name='Comment'),
),
migrations.AddField(
model_name='voucher',
name='tag',
field=models.CharField(blank=True, db_index=True, help_text='You can use this field to group multiple vouchers together. If you enter the same value for multiple vouchers, you can get statistics on how many of them have been redeemed etc.', max_length=255, verbose_name='Tag'),
),
migrations.AddField(
model_name='item',
name='hide_without_voucher',
field=models.BooleanField(default=False, help_text='This product will be hidden from the event page until the user enters a voucher code that is specifically tied to this product (and not via a quota).', verbose_name='This product will only be shown if a voucher matching the product is redeemed.'),
),
migrations.AddField(
model_name='item',
name='require_voucher',
field=models.BooleanField(default=False, help_text='To buy this product, the user needs a voucher that applies to this product either directly or via a quota.', verbose_name='This product can only be bought using a voucher.'),
),
migrations.AlterField(
model_name='logentry',
name='datetime',
field=models.DateTimeField(auto_now_add=True, db_index=True),
),
migrations.AlterField(
model_name='logentry',
name='object_id',
field=models.PositiveIntegerField(db_index=True),
),
migrations.AlterField(
model_name='order',
name='code',
field=models.CharField(db_index=True, max_length=16, verbose_name='Order code'),
),
migrations.AlterField(
model_name='order',
name='status',
field=models.CharField(choices=[('n', 'pending'), ('p', 'paid'), ('e', 'expired'), ('c', 'cancelled'), ('r', 'refunded')], db_index=True, max_length=3, verbose_name='Status'),
),
migrations.AlterField(
model_name='voucher',
name='code',
field=models.CharField(db_index=True, default=pretix.base.models.vouchers.generate_code, max_length=255, verbose_name='Voucher code'),
),
migrations.AddField(
model_name='order',
name='comment',
field=models.TextField(blank=True, help_text='The text entered in this field will not be visible to the user and is available for your convenience.', verbose_name='Comment'),
),
migrations.RemoveField(
model_name='cartposition',
name='base_price',
),
migrations.RemoveField(
model_name='cartposition',
name='voucher_discount',
),
migrations.RemoveField(
model_name='orderposition',
name='base_price',
),
migrations.RemoveField(
model_name='orderposition',
name='voucher_discount',
),
]

View File

@@ -7,10 +7,10 @@ from decimal import Decimal
import django.core.validators
import django.db.models.deletion
import i18nfield.fields
from django.conf import settings
from django.db import migrations, models
import pretix.base.i18n
import pretix.base.models.base
import pretix.base.models.items
import pretix.base.models.orders
@@ -64,7 +64,7 @@ class Migration(migrations.Migration):
name='Event',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', i18nfield.fields.I18nCharField(max_length=200, verbose_name='Name')),
('name', pretix.base.i18n.I18nCharField(max_length=200, verbose_name='Name')),
('slug', models.SlugField(help_text='Should be short, only contain lowercase letters and numbers, and must be unique among your events. This is being used in addresses and bank transfer references.', validators=[django.core.validators.RegexValidator(message='The slug may only contain letters, numbers, dots and dashes.', regex='^[a-zA-Z0-9.-]+$')], verbose_name='Slug')),
('currency', models.CharField(default='EUR', max_length=10, verbose_name='Default currency')),
('date_from', models.DateTimeField(verbose_name='Event start time')),
@@ -119,9 +119,9 @@ class Migration(migrations.Migration):
name='Item',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', i18nfield.fields.I18nCharField(max_length=255, verbose_name='Item name')),
('name', pretix.base.i18n.I18nCharField(max_length=255, verbose_name='Item name')),
('active', models.BooleanField(default=True, verbose_name='Active')),
('description', i18nfield.fields.I18nTextField(blank=True, help_text='This is shown below the product name in lists.', null=True, verbose_name='Description')),
('description', pretix.base.i18n.I18nTextField(blank=True, help_text='This is shown below the product name in lists.', null=True, verbose_name='Description')),
('default_price', models.DecimalField(decimal_places=2, max_digits=7, null=True, verbose_name='Default price')),
('tax_rate', models.DecimalField(blank=True, decimal_places=2, max_digits=7, null=True, verbose_name='Taxes included in percent')),
('admission', models.BooleanField(default=False, help_text='Whether or not buying this product allows a person to enter your event', verbose_name='Is an admission ticket')),
@@ -141,7 +141,7 @@ class Migration(migrations.Migration):
name='ItemCategory',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', i18nfield.fields.I18nCharField(max_length=255, verbose_name='Category name')),
('name', pretix.base.i18n.I18nCharField(max_length=255, verbose_name='Category name')),
('position', models.IntegerField(default=0)),
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='categories', to='pretixbase.Event')),
],
@@ -156,7 +156,7 @@ class Migration(migrations.Migration):
name='ItemVariation',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('value', i18nfield.fields.I18nCharField(max_length=255, verbose_name='Description')),
('value', pretix.base.i18n.I18nCharField(max_length=255, verbose_name='Description')),
('active', models.BooleanField(default=True, verbose_name='Active')),
('position', models.PositiveIntegerField(default=0, verbose_name='Position')),
('default_price', models.DecimalField(blank=True, decimal_places=2, max_digits=7, null=True, verbose_name='Default price')),
@@ -264,7 +264,7 @@ class Migration(migrations.Migration):
name='Question',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('question', i18nfield.fields.I18nTextField(verbose_name='Question')),
('question', pretix.base.i18n.I18nTextField(verbose_name='Question')),
('type', models.CharField(choices=[('N', 'Number'), ('S', 'Text (one line)'), ('T', 'Multiline text'), ('B', 'Yes/No')], max_length=5, verbose_name='Question type')),
('required', models.BooleanField(default=False, verbose_name='Required question')),
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='questions', to='pretixbase.Event')),

View File

@@ -3,9 +3,10 @@
from __future__ import unicode_literals
import django.db.models.deletion
import i18nfield.fields
from django.db import migrations, models
import pretix.base.i18n
class Migration(migrations.Migration):
@@ -18,7 +19,7 @@ class Migration(migrations.Migration):
name='QuestionOption',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('answer', i18nfield.fields.I18nCharField(verbose_name='Answer')),
('answer', pretix.base.i18n.I18nCharField(verbose_name='Answer')),
],
),
migrations.AlterField(

View File

@@ -2,9 +2,10 @@
# Generated by Django 1.9.4 on 2016-04-21 19:43
from __future__ import unicode_literals
import i18nfield.fields
from django.db import migrations, models
import pretix.base.i18n
class Migration(migrations.Migration):
@@ -16,7 +17,7 @@ class Migration(migrations.Migration):
migrations.AddField(
model_name='itemcategory',
name='description',
field=i18nfield.fields.I18nTextField(blank=True, verbose_name='Category description'),
field=pretix.base.i18n.I18nTextField(blank=True, verbose_name='Category description'),
),
migrations.AlterField(
model_name='questionanswer',

View File

@@ -1,212 +0,0 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-02-03 14:21
from __future__ import unicode_literals
import django.core.validators
import django.db.migrations.operations.special
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
import pretix.base.validators
def preserve_event_settings(apps, schema_editor):
Event = apps.get_model('pretixbase', 'Event')
EventSetting = apps.get_model('pretixbase', 'EventSetting')
for e in Event.objects.all():
EventSetting.objects.create(object=e, key='mail_days_order_expire_warning', value='0')
def forwards42(apps, schema_editor):
Order = apps.get_model('pretixbase', 'Order')
EventSetting = apps.get_model('pretixbase', 'EventSetting')
etz = {
s['object_id']: s['value']
for s in EventSetting.objects.filter(key='timezone').values('object_id', 'value')
}
for order in Order.objects.all():
tz = pytz.timezone(etz.get(order.event_id, 'UTC'))
order.expires = order.expires.astimezone(tz).replace(hour=23, minute=59, second=59)
order.save()
def forwards44(apps, schema_editor):
CachedTicket = apps.get_model('pretixbase', 'CachedTicket')
CachedTicket.objects.all().delete()
class Migration(migrations.Migration):
replaces = [('pretixbase', '0031_auto_20160816_0648'), ('pretixbase', '0032_question_position'), ('pretixbase', '0033_auto_20160821_2222'), ('pretixbase', '0034_auto_20160830_1952'), ('pretixbase', '0032_item_allow_cancel'), ('pretixbase', '0033_auto_20160822_1044'), ('pretixbase', '0035_merge'), ('pretixbase', '0036_auto_20160902_0755'), ('pretixbase', '0037_invoice_payment_provider_text'), ('pretixbase', '0038_auto_20160924_1448'), ('pretixbase', '0039_user_require_2fa'), ('pretixbase', '0040_u2fdevice'), ('pretixbase', '0041_auto_20161018_1654'), ('pretixbase', '0042_order_expires'), ('pretixbase', '0043_globalsetting'), ('pretixbase', '0044_auto_20161101_1610'), ('pretixbase', '0045_auto_20161108_1542'), ('pretixbase', '0046_order_meta_info'), ('pretixbase', '0047_auto_20161126_1300'), ('pretixbase', '0048_auto_20161129_1330')]
dependencies = [
('pretixbase', '0030_auto_20160816_0646'),
]
operations = [
migrations.RenameField(
model_name='invoice',
old_name='invoice_no_charfield',
new_name='invoice_no',
),
migrations.AddField(
model_name='invoice',
name='footer_text',
field=models.TextField(blank=True),
),
migrations.AddField(
model_name='invoice',
name='introductory_text',
field=models.TextField(blank=True),
),
migrations.AlterUniqueTogether(
name='invoice',
unique_together=set([('event', 'invoice_no')]),
),
migrations.AddField(
model_name='question',
name='position',
field=models.IntegerField(default=0),
),
migrations.AlterModelOptions(
name='question',
options={'ordering': ('position', 'id'), 'verbose_name': 'Question', 'verbose_name_plural': 'Questions'},
),
migrations.AddField(
model_name='item',
name='allow_cancel',
field=models.BooleanField(default=True, help_text='If you deactivate this, an order including this product might not be cancelled by the user. It may still be cancelled by you.', verbose_name='Allow product to be cancelled'),
),
migrations.AddField(
model_name='order',
name='expiry_reminder_sent',
field=models.BooleanField(default=False),
),
migrations.RunPython(
code=preserve_event_settings,
),
migrations.AddField(
model_name='invoice',
name='payment_provider_text',
field=models.TextField(blank=True),
),
migrations.AddField(
model_name='eventpermission',
name='can_view_vouchers',
field=models.BooleanField(default=True, verbose_name='Can view vouchers'),
),
migrations.AlterField(
model_name='item',
name='allow_cancel',
field=models.BooleanField(default=True, help_text='If you deactivate this, an order including this product might not be canceled by the user. It may still be canceled by you.', verbose_name='Allow product to be canceled'),
),
migrations.AlterField(
model_name='order',
name='status',
field=models.CharField(choices=[('n', 'pending'), ('p', 'paid'), ('e', 'expired'), ('c', 'canceled'), ('r', 'refunded')], db_index=True, max_length=3, verbose_name='Status'),
),
migrations.AddField(
model_name='user',
name='require_2fa',
field=models.BooleanField(default=False),
),
migrations.CreateModel(
name='U2FDevice',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(help_text='The human-readable name of this device.', max_length=64)),
('confirmed', models.BooleanField(default=True, help_text='Is this device ready for use?')),
('json_data', models.TextField()),
('user', models.ForeignKey(help_text='The user that this device belongs to.', on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
migrations.AlterField(
model_name='cachedticket',
name='cachedfile',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='pretixbase.CachedFile'),
),
migrations.RunPython(
code=forwards42,
reverse_code=django.db.migrations.operations.special.RunPython.noop,
),
migrations.CreateModel(
name='GlobalSetting',
fields=[
('key', models.CharField(max_length=255, primary_key=True, serialize=False)),
('value', models.TextField()),
],
),
migrations.RunPython(
code=forwards44,
reverse_code=django.db.migrations.operations.special.RunPython.noop,
),
migrations.RemoveField(
model_name='cachedticket',
name='order',
),
migrations.AddField(
model_name='cachedticket',
name='order_position',
field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, to='pretixbase.OrderPosition'),
preserve_default=False,
),
migrations.AlterField(
model_name='cartposition',
name='expires',
field=models.DateTimeField(db_index=True, verbose_name='Expiration date'),
),
migrations.AlterField(
model_name='voucher',
name='redeemed',
field=models.BooleanField(db_index=True, default=False, verbose_name='Redeemed'),
),
migrations.AlterField(
model_name='voucher',
name='valid_until',
field=models.DateTimeField(blank=True, db_index=True, null=True, verbose_name='Valid until'),
),
migrations.AddField(
model_name='order',
name='meta_info',
field=models.TextField(blank=True, null=True, verbose_name='Meta information'),
),
migrations.AddField(
model_name='voucher',
name='max_usages',
field=models.PositiveIntegerField(default=1, help_text='Number of times this voucher can be redeemed.', verbose_name='Maximum usages'),
),
migrations.AlterField(
model_name='event',
name='slug',
field=models.SlugField(help_text='Should be short, only contain lowercase letters and numbers, and must be unique among your events. This is being used in addresses and bank transfer references.', validators=[django.core.validators.RegexValidator(message='The slug may only contain letters, numbers, dots and dashes.', regex='^[a-zA-Z0-9.-]+$'), pretix.base.validators.EventSlugBlacklistValidator()], verbose_name='Slug'),
),
migrations.AlterField(
model_name='organizer',
name='slug',
field=models.SlugField(help_text='Should be short, only contain lowercase letters and numbers, and must be unique among your events. This is being used in addresses and bank transfer references.', validators=[django.core.validators.RegexValidator(message='The slug may only contain letters, numbers, dots and dashes.', regex='^[a-zA-Z0-9.-]+$'), pretix.base.validators.OrganizerSlugBlacklistValidator()], verbose_name='Slug'),
),
migrations.AlterField(
model_name='voucher',
name='redeemed',
field=models.PositiveIntegerField(default=0, verbose_name='Redeemed'),
),
migrations.AddField(
model_name='voucher',
name='price_mode',
field=models.CharField(choices=[('none', 'No effect'), ('set', 'Set product price to'), ('subtract', 'Subtract from product price'), ('percent', 'Reduce product price by (%)')], default='set', max_length=100, verbose_name='Price mode'),
),
migrations.RenameField(
model_name='voucher',
old_name='price',
new_name='value',
),
migrations.AlterField(
model_name='voucher',
name='value',
field=models.DecimalField(blank=True, decimal_places=2, max_digits=10, null=True, verbose_name='Voucher value'),
),
]

View File

@@ -1,30 +0,0 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-29 13:30
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0047_auto_20161126_1300'),
]
operations = [
migrations.AddField(
model_name='voucher',
name='price_mode',
field=models.CharField(choices=[('none', 'No effect'), ('set', 'Set product price to'), ('subtract', 'Subtract from product price'), ('percent', 'Reduce product price by (%)')], default='set', max_length=100, verbose_name='Price mode'),
),
migrations.RenameField(
model_name='voucher',
old_name='price',
new_name='value',
),
migrations.AlterField(
model_name='voucher',
name='value',
field=models.DecimalField(blank=True, decimal_places=2, max_digits=10, null=True, verbose_name='Voucher value'),
),
]

View File

@@ -1,29 +0,0 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2016-12-08 16:47
from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0048_auto_20161129_1330'),
('pretixdroid', '0002_auto_20161208_1644'),
]
state_operations = [
migrations.CreateModel(
name='Checkin',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('datetime', models.DateTimeField(auto_now_add=True)),
('position', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='pretixdroid_checkins', to='pretixbase.OrderPosition')),
],
),
]
operations = [
migrations.SeparateDatabaseAndState(state_operations=state_operations)
]

View File

@@ -1,31 +0,0 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2016-12-21 17:05
from __future__ import unicode_literals
from django.db import migrations, models
def forwards(apps, schema_editor):
Order = apps.get_model('pretixbase', 'Order')
for o in Order.objects.all():
for i, p in enumerate(o.positions.all()):
p.positionid = i + 1
p.save()
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0049_checkin'),
]
operations = [
migrations.AddField(
model_name='orderposition',
name='positionid',
field=models.PositiveIntegerField(default=1),
),
migrations.RunPython(
forwards, migrations.RunPython.noop
),
]

View File

@@ -1,219 +0,0 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-02-03 14:12
from __future__ import unicode_literals
import django.core.validators
import django.db.migrations.operations.special
import django.db.models.deletion
import django.utils.timezone
import i18nfield.fields
from django.conf import settings
from django.db import migrations, models
import pretix.base.models.event
import pretix.base.models.orders
import pretix.base.models.organizer
import pretix.base.validators
def forwards50(apps, schema_editor):
Order = apps.get_model('pretixbase', 'Order')
for o in Order.objects.all():
for i, p in enumerate(o.positions.all()):
p.positionid = i + 1
p.save()
def invalidate_ticket_cache(apps, schema_editor):
CachedTicket = apps.get_model('pretixbase', 'CachedTicket')
for ct in CachedTicket.objects.all():
try:
if ct.cachedfile:
ct.cachedfile.delete()
if ct.cachedfile.file:
ct.cachedfile.file.delete(False)
except models.Model.DoesNotExist:
pass
ct.delete()
def merge_names(apps, schema_editor):
User = apps.get_model('pretixbase', 'User')
for u in User.objects.all():
if u.givenname:
if u.familyname:
u.fullname = u.givenname + " " + u.familyname
else:
u.fullname = u.givenname
elif u.familyname:
u.fullname = u.familyname
u.save()
class Migration(migrations.Migration):
replaces = [('pretixbase', '0050_orderposition_positionid'), ('pretixbase', '0051_auto_20161221_1720'), ('pretixbase', '0052_auto_20161231_1533'), ('pretixbase', '0053_auto_20170104_1252'), ('pretixbase', '0054_auto_20170107_1058'), ('pretixbase', '0055_organizerpermission_can_change_permissions'), ('pretixbase', '0056_auto_20170107_1251'), ('pretixbase', '0057_auto_20170107_1531'), ('pretixbase', '0058_auto_20170107_1533'), ('pretixbase', '0059_cachedcombinedticket'), ('pretixbase', '0060_auto_20170113_1438'), ('pretixbase', '0061_event_location')]
dependencies = [
('pretixbase', '0049_checkin'),
]
operations = [
migrations.AddField(
model_name='orderposition',
name='positionid',
field=models.PositiveIntegerField(default=1),
),
migrations.RunPython(
code=forwards50,
reverse_code=django.db.migrations.operations.special.RunPython.noop,
),
migrations.RunPython(
code=invalidate_ticket_cache,
reverse_code=django.db.migrations.operations.special.RunPython.noop,
),
migrations.RemoveField(
model_name='cachedticket',
name='cachedfile',
),
migrations.AddField(
model_name='cachedticket',
name='extension',
field=models.CharField(default='', max_length=255),
preserve_default=False,
),
migrations.AddField(
model_name='cachedticket',
name='file',
field=models.FileField(blank=True, null=True, upload_to=pretix.base.models.orders.cachedticket_name),
),
migrations.AddField(
model_name='cachedticket',
name='type',
field=models.CharField(default='', max_length=255),
preserve_default=False,
),
migrations.AlterField(
model_name='checkin',
name='datetime',
field=models.DateTimeField(default=django.utils.timezone.now),
),
migrations.AlterField(
model_name='checkin',
name='position',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='checkins', to='pretixbase.OrderPosition'),
),
migrations.AlterField(
model_name='voucher',
name='price_mode',
field=models.CharField(choices=[('none', 'No effect'), ('set', 'Set product price to'), ('subtract', 'Subtract from product price'), ('percent', 'Reduce product price by (%)')], default='none', max_length=100, verbose_name='Price mode'),
),
migrations.CreateModel(
name='RequiredAction',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('datetime', models.DateTimeField(auto_now_add=True, db_index=True)),
('done', models.BooleanField(default=False)),
('action_type', models.CharField(max_length=255)),
('data', models.TextField(default='{}')),
],
options={
'ordering': ('datetime',),
},
),
migrations.AlterField(
model_name='event',
name='slug',
field=models.SlugField(help_text='Should be short, only contain lowercase letters and numbers, and must be unique among your events. This will be used in order codes, invoice numbers, links and bank transfer references.', validators=[django.core.validators.RegexValidator(message='The slug may only contain letters, numbers, dots and dashes.', regex='^[a-zA-Z0-9.-]+$'), pretix.base.validators.EventSlugBlacklistValidator()], verbose_name='Short form'),
),
migrations.AddField(
model_name='requiredaction',
name='event',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='pretixbase.Event'),
),
migrations.AddField(
model_name='requiredaction',
name='user',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='eventpermission',
name='invite_email',
field=models.EmailField(blank=True, max_length=254, null=True),
),
migrations.AddField(
model_name='eventpermission',
name='invite_token',
field=models.CharField(blank=True, default=pretix.base.models.event.generate_invite_token, max_length=64, null=True),
),
migrations.AlterField(
model_name='eventpermission',
name='user',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='event_perms', to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='organizerpermission',
name='can_change_permissions',
field=models.BooleanField(default=True, verbose_name='Can change permissions'),
),
migrations.AddField(
model_name='organizerpermission',
name='invite_email',
field=models.EmailField(blank=True, max_length=254, null=True),
),
migrations.AddField(
model_name='organizerpermission',
name='invite_token',
field=models.CharField(blank=True, default=pretix.base.models.organizer.generate_invite_token, max_length=64, null=True),
),
migrations.AlterField(
model_name='organizerpermission',
name='user',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='organizer_perms', to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='user',
name='fullname',
field=models.CharField(blank=True, max_length=255, null=True, verbose_name='Full name'),
),
migrations.AlterField(
model_name='organizer',
name='slug',
field=models.SlugField(help_text='Should be short, only contain lowercase letters and numbers, and must be unique among your events. This is being used in addresses and bank transfer references.', validators=[django.core.validators.RegexValidator(message='The slug may only contain letters, numbers, dots and dashes.', regex='^[a-zA-Z0-9.-]+$'), pretix.base.validators.OrganizerSlugBlacklistValidator()], verbose_name='Short form'),
),
migrations.RunPython(
code=merge_names,
reverse_code=django.db.migrations.operations.special.RunPython.noop,
),
migrations.RemoveField(
model_name='user',
name='familyname',
),
migrations.RemoveField(
model_name='user',
name='givenname',
),
migrations.CreateModel(
name='CachedCombinedTicket',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('provider', models.CharField(max_length=255)),
('type', models.CharField(max_length=255)),
('extension', models.CharField(max_length=255)),
('file', models.FileField(blank=True, null=True, upload_to=pretix.base.models.orders.cachedcombinedticket_name)),
('order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='pretixbase.Order')),
('created', models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now)),
],
),
migrations.AddField(
model_name='cachedticket',
name='created',
field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
migrations.AddField(
model_name='event',
name='location',
field=i18nfield.fields.I18nCharField(blank=True, max_length=200, null=True, verbose_name='Location'),
),
]

View File

@@ -1,54 +0,0 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2016-12-21 17:20
from __future__ import unicode_literals
from django.db import migrations, models
import pretix.base.models.orders
def invalidate_ticket_cache(apps, schema_editor):
CachedTicket = apps.get_model('pretixbase', 'CachedTicket')
for ct in CachedTicket.objects.all():
try:
if ct.cachedfile:
ct.cachedfile.delete()
if ct.cachedfile.file:
ct.cachedfile.file.delete(False)
except models.Model.DoesNotExist:
pass
ct.delete()
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0050_orderposition_positionid'),
]
operations = [
migrations.RunPython(
invalidate_ticket_cache, migrations.RunPython.noop
),
migrations.RemoveField(
model_name='cachedticket',
name='cachedfile',
),
migrations.AddField(
model_name='cachedticket',
name='extension',
field=models.CharField(default='', max_length=255),
preserve_default=False,
),
migrations.AddField(
model_name='cachedticket',
name='file',
field=models.FileField(blank=True, null=True, upload_to=pretix.base.models.orders.cachedticket_name),
),
migrations.AddField(
model_name='cachedticket',
name='type',
field=models.CharField(default='', max_length=255),
preserve_default=False,
),
]

View File

@@ -1,42 +0,0 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-02-06 20:27
from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
import pretix.base.models.base
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0050_orderposition_positionid_squashed_0061_event_location'),
]
operations = [
migrations.CreateModel(
name='WaitingListEntry',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(auto_now_add=True, verbose_name='On waiting list since')),
('email', models.EmailField(max_length=254, verbose_name='E-mail address')),
('locale', models.CharField(default='en', max_length=190)),
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='waitinglistentries', to='pretixbase.Event', verbose_name='Event')),
('item', models.ForeignKey(help_text='The product the user waits for.', on_delete=django.db.models.deletion.CASCADE, related_name='waitinglistentries', to='pretixbase.Item', verbose_name='Product')),
('variation', models.ForeignKey(blank=True, help_text='The variation of the product selected above.', null=True, on_delete=django.db.models.deletion.CASCADE, related_name='waitinglistentries', to='pretixbase.ItemVariation', verbose_name='Product variation')),
('voucher', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='pretixbase.Voucher', verbose_name='Assigned voucher')),
],
options={
'ordering': ['created'],
'verbose_name': 'Waiting list entry',
'verbose_name_plural': 'Waiting list entries',
},
bases=(models.Model, pretix.base.models.base.LoggingMixin),
),
migrations.AlterField(
model_name='cachedcombinedticket',
name='created',
field=models.DateTimeField(auto_now_add=True),
),
]

File diff suppressed because one or more lines are too long

View File

@@ -1,32 +0,0 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2016-12-31 15:33
from __future__ import unicode_literals
import django.db.models.deletion
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0051_auto_20161221_1720'),
]
operations = [
migrations.AlterField(
model_name='checkin',
name='datetime',
field=models.DateTimeField(default=django.utils.timezone.now),
),
migrations.AlterField(
model_name='checkin',
name='position',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='checkins', to='pretixbase.OrderPosition'),
),
migrations.AlterField(
model_name='voucher',
name='price_mode',
field=models.CharField(choices=[('none', 'No effect'), ('set', 'Set product price to'), ('subtract', 'Subtract from product price'), ('percent', 'Reduce product price by (%)')], default='none', max_length=100, verbose_name='Price mode'),
),
]

View File

@@ -1,38 +0,0 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-24 15:06
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0051_auto_20170206_2027'),
]
operations = [
migrations.AlterModelOptions(
name='invoice',
options={'ordering': ('invoice_no',)},
),
migrations.AlterModelOptions(
name='orderposition',
options={'ordering': ('positionid', 'id'), 'verbose_name': 'Order position', 'verbose_name_plural': 'Order positions'},
),
migrations.AddField(
model_name='item',
name='max_per_order',
field=models.IntegerField(blank=True, help_text='This product can only be bought at most this times within one order. If you keep the field empty or set it to 0, there is no special limit for this product. The limit for the maximum number of items in the whole order applies regardless.', null=True, verbose_name='Maximum times per order'),
),
migrations.AlterField(
model_name='item',
name='allow_cancel',
field=models.BooleanField(default=True, help_text='If this is active and the general event settings allo wit, orders containing this product can be canceled by the user until the order is paid for. Users cannot cancel paid orders on their own and you can cancel orders at all times, regardless of this setting', verbose_name='Allow product to be canceled'),
),
migrations.AlterField(
model_name='item',
name='default_price',
field=models.DecimalField(decimal_places=2, help_text='If this product has multiple variations, you can set different prices for each of the variations. If a variation does not have a special price or if you do not have variations, this price will be used.', max_digits=7, null=True, verbose_name='Default price'),
),
]

View File

@@ -1,114 +0,0 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-04-27 09:11
from __future__ import unicode_literals
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
import pretix.base.models.organizer
def create_teams(apps, schema_editor):
Event = apps.get_model('pretixbase', 'Event')
Organizer = apps.get_model('pretixbase', 'Organizer')
Team = apps.get_model('pretixbase', 'Team')
TeamInvite = apps.get_model('pretixbase', 'TeamInvite')
EventPermission = apps.get_model('pretixbase', 'EventPermission')
OrganizerPermission = apps.get_model('pretixbase', 'OrganizerPermission')
for o in Organizer.objects.prefetch_related('events'):
for e in o.events.all():
teams = {}
for p in e.user_perms.all():
pkey = (p.can_change_settings, p.can_change_items, p.can_view_orders,
p.can_change_permissions, p.can_change_orders, p.can_view_vouchers,
p.can_change_vouchers)
if pkey not in teams:
team = Team()
team.can_change_event_settings = p.can_change_settings
team.can_change_items = p.can_change_items
team.can_view_orders = p.can_view_orders
team.can_change_orders = p.can_change_orders
team.can_view_vouchers = p.can_view_vouchers
team.can_change_vouchers = p.can_change_vouchers
team.organizer = o
team.name = '{} Team {}'.format(
str(e.name), len(teams) + 1
)
team.save()
team.limit_events.add(e)
teams[pkey] = team
if p.user:
teams[pkey].members.add(p.user)
else:
teams[pkey].invites.create(email=p.invite_email, token=p.invite_token)
teams = {}
for p in o.user_perms.all():
pkey = (p.can_create_events, p.can_change_permissions)
if pkey not in teams:
team = Team()
team.can_change_organizer_settings = True
team.can_create_events = p.can_create_events
team.can_change_teams = p.can_change_permissions
team.organizer = o
team.name = '{} Team {}'.format(
str(o.name), len(teams) + 1
)
team.save()
teams[pkey] = team
if p.user:
teams[pkey].members.add(p.user)
else:
teams[pkey].invites.create(email=p.invite_email, token=p.invite_token)
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0051_auto_20170206_2027_squashed_0057_auto_20170501_2116'),
]
operations = [
migrations.CreateModel(
name='Team',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=190, verbose_name='Team name')),
('all_events', models.BooleanField(default=False, verbose_name='All events (including newly created ones)')),
('can_create_events', models.BooleanField(default=False, verbose_name='Can create events')),
('can_change_teams', models.BooleanField(default=False, verbose_name='Can change permissions')),
('can_change_organizer_settings', models.BooleanField(default=False, verbose_name='Can change organizer settings')),
('can_change_event_settings', models.BooleanField(default=False, verbose_name='Can change event settings')),
('can_change_items', models.BooleanField(default=False, verbose_name='Can change product settings')),
('can_view_orders', models.BooleanField(default=False, verbose_name='Can view orders')),
('can_change_orders', models.BooleanField(default=False, verbose_name='Can change orders')),
('can_view_vouchers', models.BooleanField(default=False, verbose_name='Can view vouchers')),
('can_change_vouchers', models.BooleanField(default=False, verbose_name='Can change vouchers')),
('limit_events', models.ManyToManyField(to='pretixbase.Event', verbose_name='Limit to events')),
('members', models.ManyToManyField(related_name='teams', to=settings.AUTH_USER_MODEL, verbose_name='Team members')),
('organizer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='teams', to='pretixbase.Organizer')),
],
options={
'verbose_name_plural': 'Teams',
'verbose_name': 'Team',
},
),
migrations.CreateModel(
name='TeamInvite',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('email', models.EmailField(blank=True, max_length=254, null=True)),
('token', models.CharField(blank=True, default=pretix.base.models.organizer.generate_invite_token, max_length=64, null=True)),
('team', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='invites', to='pretixbase.Team')),
],
),
migrations.RunPython(
create_teams, migrations.RunPython.noop
)
]

View File

@@ -1,48 +0,0 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-04 12:52
from __future__ import unicode_literals
import django.core.validators
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
import pretix.base.validators
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0052_auto_20161231_1533'),
]
operations = [
migrations.CreateModel(
name='RequiredAction',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('datetime', models.DateTimeField(auto_now_add=True, db_index=True)),
('done', models.BooleanField(default=False)),
('action_type', models.CharField(max_length=255)),
('data', models.TextField(default='{}')),
],
options={
'ordering': ('datetime',),
},
),
migrations.AlterField(
model_name='event',
name='slug',
field=models.SlugField(help_text='Should be short, only contain lowercase letters and numbers, and must be unique among your events. This will be used in order codes, invoice numbers, links and bank transfer references.', validators=[django.core.validators.RegexValidator(message='The slug may only contain letters, numbers, dots and dashes.', regex='^[a-zA-Z0-9.-]+$'), pretix.base.validators.EventSlugBlacklistValidator()], verbose_name='Short form'),
),
migrations.AddField(
model_name='requiredaction',
name='event',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='pretixbase.Event'),
),
migrations.AddField(
model_name='requiredaction',
name='user',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL),
),
]

View File

@@ -1,59 +0,0 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-04-09 16:51
from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
def migrate_global_settings(apps, schema_editor):
GlobalSetting = apps.get_model('pretixbase', 'GlobalSetting')
GlobalSettingsObject_SettingsStore = apps.get_model('pretixbase', 'GlobalSettingsObject_SettingsStore')
l = []
for s in GlobalSetting.objects.all():
l.append(GlobalSettingsObject_SettingsStore(key=s.key, value=s.value))
GlobalSettingsObject_SettingsStore.objects.bulk_create(l)
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0052_auto_20170324_1506'),
]
operations = [
migrations.RenameModel(
old_name='EventSetting',
new_name='Event_SettingsStore',
),
migrations.RenameModel(
old_name='OrganizerSetting',
new_name='Organizer_SettingsStore',
),
migrations.CreateModel(
name='GlobalSettingsObject_SettingsStore',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('key', models.CharField(db_index=True, max_length=255)),
('value', models.TextField()),
],
),
migrations.RunPython(
migrate_global_settings, migrations.RunPython.noop
),
migrations.DeleteModel(
name='GlobalSetting',
),
migrations.AlterField(
model_name='event_settingsstore',
name='object',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='_settings_objects', to='pretixbase.Event'),
),
migrations.AlterField(
model_name='organizer_settingsstore',
name='object',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='_settings_objects', to='pretixbase.Organizer'),
),
]

View File

@@ -1,34 +0,0 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-07 10:58
from __future__ import unicode_literals
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
import pretix.base.models.event
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0053_auto_20170104_1252'),
]
operations = [
migrations.AddField(
model_name='eventpermission',
name='invite_email',
field=models.EmailField(blank=True, max_length=254, null=True),
),
migrations.AddField(
model_name='eventpermission',
name='invite_token',
field=models.CharField(blank=True, default=pretix.base.models.event.generate_invite_token, max_length=64, null=True),
),
migrations.AlterField(
model_name='eventpermission',
name='user',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='event_perms', to=settings.AUTH_USER_MODEL),
),
]

File diff suppressed because one or more lines are too long

View File

@@ -1,40 +0,0 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-04-13 15:37
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0054_auto_20170413_1050'),
]
operations = [
migrations.AddField(
model_name='cartposition',
name='attendee_email',
field=models.EmailField(blank=True, help_text='Empty, if this product is not an admission ticket', max_length=254, null=True, verbose_name='Attendee email'),
),
migrations.AddField(
model_name='orderposition',
name='attendee_email',
field=models.EmailField(blank=True, help_text='Empty, if this product is not an admission ticket', max_length=254, null=True, verbose_name='Attendee email'),
),
migrations.AlterField(
model_name='event_settingsstore',
name='key',
field=models.CharField(max_length=255),
),
migrations.AlterField(
model_name='globalsettingsobject_settingsstore',
name='key',
field=models.CharField(max_length=255),
),
migrations.AlterField(
model_name='organizer_settingsstore',
name='key',
field=models.CharField(max_length=255),
),
]

View File

@@ -1,20 +0,0 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-07 12:37
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0054_auto_20170107_1058'),
]
operations = [
migrations.AddField(
model_name='organizerpermission',
name='can_change_permissions',
field=models.BooleanField(default=True, verbose_name='Can change permissions'),
),
]

View File

@@ -1,34 +0,0 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-07 12:51
from __future__ import unicode_literals
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
import pretix.base.models.organizer
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0055_organizerpermission_can_change_permissions'),
]
operations = [
migrations.AddField(
model_name='organizerpermission',
name='invite_email',
field=models.EmailField(blank=True, max_length=254, null=True),
),
migrations.AddField(
model_name='organizerpermission',
name='invite_token',
field=models.CharField(blank=True, default=pretix.base.models.organizer.generate_invite_token, max_length=64, null=True),
),
migrations.AlterField(
model_name='organizerpermission',
name='user',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='organizer_perms', to=settings.AUTH_USER_MODEL),
),
]

View File

@@ -1,58 +0,0 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-04-14 10:44
from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0055_auto_20170413_1537'),
]
operations = [
migrations.CreateModel(
name='ItemAddOn',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('min_count', models.PositiveIntegerField(default=0, verbose_name='Minimum number')),
('max_count', models.PositiveIntegerField(default=1, verbose_name='Maximum number')),
],
),
migrations.AddField(
model_name='cartposition',
name='addon_to',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='addons', to='pretixbase.CartPosition'),
),
migrations.AddField(
model_name='itemcategory',
name='is_addon',
field=models.BooleanField(default=False, help_text='If selected, the products belonging to this category are not for sale on their own. They can only be bought in combination with a product that has this category configured as a possible source for add-ons.', verbose_name='Products in this category are add-on products'),
),
migrations.AddField(
model_name='orderposition',
name='addon_to',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='addons', to='pretixbase.OrderPosition'),
),
migrations.AlterField(
model_name='item',
name='free_price',
field=models.BooleanField(default=False, help_text='If this option is active, your users can choose the price themselves. The price configured above is then interpreted as the minimum price a user has to enter. You could use this e.g. to collect additional donations for your event. This is currently not supported for products that are bought as an add-on to other products.', verbose_name='Free price input'),
),
migrations.AddField(
model_name='itemaddon',
name='addon_category',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='addon_to', to='pretixbase.ItemCategory', verbose_name='Category'),
),
migrations.AddField(
model_name='itemaddon',
name='base_item',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='addons', to='pretixbase.Item'),
),
migrations.AlterUniqueTogether(
name='itemaddon',
unique_together=set([('base_item', 'addon_category')]),
),
]

View File

@@ -1,42 +0,0 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-07 15:31
from __future__ import unicode_literals
import django.core.validators
from django.db import migrations, models
import pretix.base.validators
def merge_names(apps, schema_editor):
User = apps.get_model('pretixbase', 'User')
for u in User.objects.all():
if u.givenname:
if u.familyname:
u.fullname = u.givenname + " " + u.familyname
else:
u.fullname = u.givenname
elif u.familyname:
u.fullname = u.familyname
u.save()
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0056_auto_20170107_1251'),
]
operations = [
migrations.AddField(
model_name='user',
name='fullname',
field=models.CharField(blank=True, max_length=255, null=True, verbose_name='Full name'),
),
migrations.AlterField(
model_name='organizer',
name='slug',
field=models.SlugField(help_text='Should be short, only contain lowercase letters and numbers, and must be unique among your events. This is being used in addresses and bank transfer references.', validators=[django.core.validators.RegexValidator(message='The slug may only contain letters, numbers, dots and dashes.', regex='^[a-zA-Z0-9.-]+$'), pretix.base.validators.OrganizerSlugBlacklistValidator()], verbose_name='Short form'),
),
migrations.RunPython(merge_names, migrations.RunPython.noop)
]

View File

@@ -1,30 +0,0 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-05-01 21:16
from __future__ import unicode_literals
import i18nfield.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0056_auto_20170414_1044'),
]
operations = [
migrations.AlterModelOptions(
name='itemaddon',
options={'ordering': ('position', 'pk')},
),
migrations.AddField(
model_name='itemaddon',
name='position',
field=models.PositiveIntegerField(default=0, verbose_name='Position'),
),
migrations.AddField(
model_name='itemvariation',
name='description',
field=i18nfield.fields.I18nTextField(blank=True, help_text='This is shown below the variation name in lists.', null=True, verbose_name='Description'),
),
]

View File

@@ -1,23 +0,0 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-07 15:33
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0057_auto_20170107_1531'),
]
operations = [
migrations.RemoveField(
model_name='user',
name='familyname',
),
migrations.RemoveField(
model_name='user',
name='givenname',
),
]

View File

@@ -1,55 +0,0 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-04-29 10:20
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0052_team_teaminvite'),
]
operations = [
migrations.RemoveField(
model_name='eventpermission',
name='event',
),
migrations.RemoveField(
model_name='eventpermission',
name='user',
),
migrations.RemoveField(
model_name='organizerpermission',
name='organizer',
),
migrations.RemoveField(
model_name='organizerpermission',
name='user',
),
migrations.RemoveField(
model_name='event',
name='permitted',
),
migrations.RemoveField(
model_name='organizer',
name='permitted',
),
migrations.AlterField(
model_name='team',
name='can_change_teams',
field=models.BooleanField(default=False, verbose_name='Can change teams and permissions'),
),
migrations.AlterField(
model_name='team',
name='limit_events',
field=models.ManyToManyField(blank=True, to='pretixbase.Event', verbose_name='Limit to events'),
),
migrations.DeleteModel(
name='EventPermission',
),
migrations.DeleteModel(
name='OrganizerPermission',
),
]

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