haldis/app/forms.py

70 lines
2.2 KiB
Python
Raw Normal View History

2015-03-31 20:15:22 +02:00
from datetime import datetime, timedelta
2015-03-31 20:15:22 +02:00
from flask import session
2017-01-06 12:05:31 +01:00
from flask_login import current_user
from flask_wtf import FlaskForm as Form
2019-09-05 03:33:29 +02:00
from wtforms import DateTimeField, SelectField, StringField, SubmitField, validators
2017-01-06 12:05:31 +01:00
from models import Location, User
from utils import euro_string
2015-03-31 20:15:22 +02:00
class OrderForm(Form):
2019-09-05 03:33:29 +02:00
courrier_id = SelectField("Courrier", coerce=int)
location_id = SelectField(
"Location", coerce=int, validators=[validators.required()]
)
starttime = DateTimeField(
"Starttime", default=datetime.now, format="%d-%m-%Y %H:%M"
)
stoptime = DateTimeField("Stoptime", format="%d-%m-%Y %H:%M")
submit_button = SubmitField("Submit")
2015-03-31 20:15:22 +02:00
def populate(self):
if current_user.is_admin():
2019-09-05 03:33:29 +02:00
self.courrier_id.choices = [(0, None)] + [
(u.id, u.username) for u in User.query.order_by("username")
]
2015-03-31 20:15:22 +02:00
else:
2019-09-05 03:33:29 +02:00
self.courrier_id.choices = [
(0, None),
(current_user.id, current_user.username),
]
self.location_id.choices = [
(l.id, l.name) for l in Location.query.order_by("name")
]
2015-03-31 20:15:22 +02:00
if self.stoptime.data is None:
self.stoptime.data = datetime.now() + timedelta(hours=1)
class OrderItemForm(Form):
2019-09-05 03:33:29 +02:00
product_id = SelectField("Item", coerce=int)
extra = StringField("Extra")
submit_button = SubmitField("Submit")
2015-03-31 20:15:22 +02:00
def populate(self, location):
2019-09-05 03:33:29 +02:00
self.product_id.choices = [
(i.id, (i.name + ": " + euro_string(i.price))) for i in location.products
]
2015-03-31 20:15:22 +02:00
class AnonOrderItemForm(OrderItemForm):
2019-09-05 03:33:29 +02:00
name = StringField("Name", validators=[validators.required()])
2015-03-31 20:15:22 +02:00
def populate(self, location):
OrderItemForm.populate(self, location)
if self.name.data is None:
2019-09-05 03:33:29 +02:00
self.name.data = session.get("anon_name", None)
2015-03-31 20:15:22 +02:00
def validate(self):
rv = OrderForm.validate(self)
if not rv:
return False
# check if we have a user with this name
user = User.query.filter_by(username=self.name.data).first()
if user is not None:
2019-09-05 03:33:29 +02:00
self.name.errors.append("Name already in use")
2015-03-31 20:15:22 +02:00
return False
return True