summaryrefslogtreecommitdiff
path: root/talerbank/app/models.py
blob: 369a84cb76eddb067fe306dc844b7113f22fdeab (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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
##
# This file is part of TALER
#  (C) 2014, 2015, 2016 INRIA
#
#  TALER is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation; either version 3, or
# (at your option) any later version. TALER is distributed in the
# hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License
# along with TALER; see the file COPYING.  If not, see
# <http://www.gnu.org/licenses/>
#
#  @author Marcello Stanisci
#  @author Florian Dold

from __future__ import unicode_literals
from typing import Any, Tuple
from django.contrib.auth.models import User
from django.db import models
from django.conf import settings
from django.core.exceptions import \
    ValidationError, \
    ObjectDoesNotExist
from .amount import Amount, BadFormatAmount, NumberTooBig

class InvalidAmount(Amount):
    def __init__(self, currency):
        super(InvalidAmount, self).__init__(currency, value=float('nan'), fraction=float('nan'))

    def stringify(self, ndigits, pretty):
        return "Invalid Amount, please report"
    def dump(self):
        return "Invalid Amount, please report"

##
# Helper function that instantiates a zero-valued @a Amount
# object.
def get_zero_amount() -> Amount:
    return Amount(settings.TALER_CURRENCY)


##
# Custom implementation of the @a Amount class as a database type.
class AmountField(models.Field):
    description = 'Amount object in Taler style'

    ##
    # Return the database type of the serialized amount.
    #
    # @param self the object itself.
    # @param connection the database connection.
    # @return type of the serialized amount: varchar.
    def db_type(self, connection: Any) -> str:
        return "varchar"

    ##
    # Stringifies the Amount object to feed the DB connector.
    #
    # @param self the object itself.
    # @para value the @a Amount object to be serialized.
    def get_prep_value(self, value: Amount) -> str:
        if not value:
            return "%s:0.0" % settings.TALER_CURRENCY
        if settings.TALER_CURRENCY != value.currency:
            raise CurrencyMismatch(settings.TALER_CURRENCY,
                                   value.currency)
        return value.stringify(settings.TALER_DIGITS)

    ##
    # Parse the stringified Amount back to Python.
    #
    # @param value serialized amount coming from the database.
    #        (It is just a string in the usual CURRENCY:X.Y form)
    # @param args currently unused.
    # @return the @a Amount object.
    @staticmethod
    def from_db_value(value: str, *args) -> Amount:
        del args # pacify PEP checkers
        if value is None:
            return Amount.parse(settings.TALER_CURRENCY)
        try:
            return Amount.parse(value)
        except NumberTooBig:
            # Keep the currency right to avoid causing
            # exceptions if some operation is attempted
            # against this invalid amount.  NOTE that the
            # value is defined as NaN, so no actual/useful
            # amount will ever be generated using this one.
            # And more, the NaN value will make it easier
            # to scan the database to find these faulty
            # amounts.
            # We also decide to not raise exception here
            # because they would propagate in too many places
            # in the code, and it would be too verbose to
            # just try-cactch any possible exception situation.
            return InvalidAmount(settings.TALER_CURRENCY)


    ##
    # Parse the stringified Amount back to Python. FIXME:
    # why this serializer consider _more_ cases respect to the
    # one above ('from_db_value')?
    #
    # @param value serialized amount coming from the database.
    #        (It is just a string in the usual CURRENCY:X.Y form)
    # @param args currently unused.
    # @return the @a Amount object.
    def to_python(self, value: Any) -> Amount:
        if isinstance(value, Amount):
            return value
        try:
            if value is None:
                return Amount.parse(settings.TALER_CURRENCY)
            return Amount.parse(value)
        except BadFormatAmount:
            raise ValidationError(
                "Invalid input for an amount string: %s" % value)


##
# Exception class to raise when a non-existent bank account is
# tried to be referenced.
class BankAccountDoesNotExist(ObjectDoesNotExist):
    hint = "Specified bank account does not exist"
    http_status_code = 404


##
# Exception class to raise when a non-existent bank transaction is
# tried to be referenced.
class BankTransactionDoesNotExist(ObjectDoesNotExist):
    hint = "Specified bank transaction does not exist"
    http_status_code = 404



##
# The class representing a bank account.
class BankAccount(models.Model):
    is_public = models.BooleanField(default=False)
    debit = models.BooleanField(default=False)
    account_no = models.AutoField(primary_key=True)
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    amount = AmountField(default=get_zero_amount)
    DoesNotExist = BankAccountDoesNotExist


##
# The class representing a bank transaction.
class BankTransaction(models.Model):
    amount = AmountField(default=False)
    debit_account = models.ForeignKey(
        BankAccount,
        on_delete=models.CASCADE,
        db_index=True,
        related_name="debit_account")
    credit_account = models.ForeignKey(
        BankAccount,
        on_delete=models.CASCADE,
        db_index=True,
        related_name="credit_account")
    subject = models.CharField(
        default="(no subject given)", max_length=200)
    date = models.DateTimeField(
        auto_now=True, db_index=True)
    cancelled = models.BooleanField(default=False)