summaryrefslogtreecommitdiffstats
path: root/bitvend/forms.py
blob: 84805e116954fccd858af83c8e64e1e922423d7f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from flask_wtf import FlaskForm
from wtforms import StringField
from flask_login import current_user
from bitvend.models import User
from wtforms.fields.core import DecimalField
from wtforms.validators import DataRequired, NumberRange, ValidationError
from decimal import Decimal, InvalidOperation


class DecimalUnityField(DecimalField):
    unity = 100

    def __init__(self, label=None, validators=None, unity=100, **kwargs):
        super(DecimalUnityField, self).__init__(label, validators, **kwargs)
        self.unity = unity

    def _value(self):
        if self.data is not None:
            format = '%%0.%df' % self.places
            return (format % (Decimal(self.data) / self.unity,))
        elif self.raw_data:
            return self.raw_data[0]

    def process_formdata(self, valuelist):
        if valuelist:
            try:
                self.data = int(Decimal(valuelist[0]) * self.unity)
            except InvalidOperation:
                self.data = None

def UserExists(form, field):
    if not User.query.get(field.data):
        raise ValidationError('User does not exist.')

def NotCurrentUser(form, field):
    if field.data == current_user.uid:
        raise ValidationError('Are you serious?')

class TransferForm(FlaskForm):
    target = StringField("Target user", validators=[
        DataRequired(), UserExists, NotCurrentUser])
    amount = DecimalUnityField("Amount", default=0, validators=[
        NumberRange(min=1),
        ])

class ManualForm(FlaskForm):
    amount = DecimalUnityField("Amount", default=0, validators=[
        ])