Completed
Push — master ( d2aebd...b0ae7e )
by
unknown
01:01
created

Lost   A

Complexity

Total Complexity 1

Size/Duplication

Total Lines 4
Duplicated Lines 0 %
Metric Value
dl 0
loc 4
rs 10
wmc 1

1 Method

Rating   Name   Duplication   Size   Complexity  
A __init__() 0 2 1
1
from .model import *
2
from . import account
3
from . import event
4
from . import item
5
from . import box
6
from . import user
7
from chezbetty import utility
8
9
import arrow
10
from pyramid.threadlocal import get_current_registry
11
12
13
class Transaction(Base):
14
    __tablename__ = 'transactions'
15
16
    id                 = Column(Integer, primary_key=True, nullable=False)
17
18
    event_id           = Column(Integer, ForeignKey("events.id"))
19
20
    to_account_virt_id = Column(Integer, ForeignKey("accounts.id"))
21
    fr_account_virt_id = Column(Integer, ForeignKey("accounts.id"))
22
    to_account_cash_id = Column(Integer, ForeignKey("accounts.id"))
23
    fr_account_cash_id = Column(Integer, ForeignKey("accounts.id"))
24
    amount             = Column(Numeric, nullable=False)
25
26
                                        # Virtual Transaction Meaning     # Cash Transaction Meaning  # Notes required?
27
    type = Column(Enum("purchase",      # user_account -> chezbetty.        None
28
                       "deposit",
29
                       "cashdeposit",   # null         -> user_account.     null      -> cashbox.
30
                       "ccdeposit",     # null         -> user_account.     null      -> chezbetty
31
                       "btcdeposit",    # null         -> user_account      null      -> btcbox
32
                       "adjustment",    # chezbetty   <-> user              None                            Yes
33
                       "restock",       # chezbetty    -> null              chezbetty -> null
34
                       "inventory",     # chezbetty   <-> null              None
35
                       "emptycashbox",  # None                              cashbox   -> safe
36
                       "emptysafe",     # None                              safe      -> chezbetty
37
                       "emptybitcoin",  # None                              btcbox    -> chezbetty
38
                       "lost",          # None                              chezbetty/cashbox/btcbox -> null       Yes
39
                       "found",         # None                              null      -> chezbetty/cashbox/btcbox  Yes
40
                       "donation",      # null         -> chezbetty         null      -> chezbetty          Yes
41
                       "withdrawal",    # chezbetty    -> null              chezbetty -> null               Yes
42
                       name="transaction_type"), nullable=False)
43
    __mapper_args__ = {'polymorphic_on': type}
44
45
46
    to_account_virt = relationship(account.Account,
47
        foreign_keys=[to_account_virt_id,],
48
        backref="transactions_to_virt"
49
    )
50
    fr_account_virt = relationship(account.Account,
51
        foreign_keys=[fr_account_virt_id,],
52
        backref="transactions_from_virt"
53
    )
54
55
    to_account_cash = relationship(account.Account,
56
        foreign_keys=[to_account_cash_id,],
57
        backref="transactions_to_cash"
58
    )
59
    fr_account_cash = relationship(account.Account,
60
        foreign_keys=[fr_account_cash_id,],
61
        backref="transactions_from_cash"
62
    )
63
    event = relationship(event.Event,
64
        foreign_keys=[event_id,],
65
        backref="transactions"
66
    )
67
68
69
    def __init__(self, event, fr_acct_virt, to_acct_virt, fr_acct_cash, to_acct_cash, amount):
70
        self.to_account_virt_id = to_acct_virt.id if to_acct_virt else None
71
        self.fr_account_virt_id = fr_acct_virt.id if fr_acct_virt else None
72
        self.to_account_cash_id = to_acct_cash.id if to_acct_cash else None
73
        self.fr_account_cash_id = fr_acct_cash.id if fr_acct_cash else None
74
75
        self.to_acct_virt = to_acct_virt
76
        self.fr_acct_virt = fr_acct_virt
77
        self.to_acct_cash = to_acct_cash
78
        self.fr_acct_cash = fr_acct_cash
79
80
        self.event_id = event.id
81
        self.amount = amount
82
83
        # Update the balances of the accounts we are moving money between
84
        if to_acct_virt:
85
            to_acct_virt.balance += self.amount
86
        if fr_acct_virt:
87
            fr_acct_virt.balance -= self.amount
88
89
        if to_acct_cash:
90
            to_acct_cash.balance += self.amount
91
        if fr_acct_cash:
92
            fr_acct_cash.balance -= self.amount
93
94
    def update_amount(self, amount):
95
        # Remove the balance we added before (upon init or last update_amount)
96
        if self.to_acct_virt:
97
            self.to_acct_virt.balance -= self.amount
98
        if self.fr_acct_virt:
99
            self.fr_acct_virt.balance += self.amount
100
        if self.to_acct_cash:
101
            self.to_acct_cash.balance -= self.amount
102
        if self.fr_acct_cash:
103
            self.fr_acct_cash.balance += self.amount
104
105
        # Save the amount so we can subtract it later if needed
106
        self.amount = amount
107
108
        # Apply the new amount
109
        if self.to_acct_virt:
110
            self.to_acct_virt.balance += self.amount
111
        if self.fr_acct_virt:
112
            self.fr_acct_virt.balance -= self.amount
113
        if self.to_acct_cash:
114
            self.to_acct_cash.balance += self.amount
115
        if self.fr_acct_cash:
116
            self.fr_acct_cash.balance -= self.amount
117
118
    @classmethod
119
    def from_id(cls, id):
120
        return DBSession.query(cls)\
121
                        .filter(cls.id == id).one()
122
123
    @classmethod
124
    def get_balance(cls, trans_type, account_obj):
125
        return DBSession.query(coalesce(func.sum(cls.amount), 0).label("balance"))\
126
                     .join(event.Event)\
127
                     .filter(or_(cls.fr_account_cash_id==account_obj.id,
128
                                 cls.to_account_cash_id==account_obj.id,
129
                                 cls.fr_account_virt_id==account_obj.id,
130
                                 cls.to_account_virt_id==account_obj.id))\
131
                     .filter(cls.type==trans_type)\
132
                     .filter(event.Event.deleted==False).one()
133
134
    @classmethod
135
    def count(cls, trans_type=None):
136
        if not trans_type:
137
            return DBSession.query(func.count(cls.id).label('c'))\
138
                            .join(event.Event)\
139
                            .filter(event.Event.deleted==False).one().c
140
        else:
141
            return DBSession.query(func.count(cls.id).label('c'))\
142
                            .join(event.Event)\
143
                            .filter(cls.type==trans_type)\
144
                            .filter(event.Event.deleted==False).one().c
145
146
    @classmethod
147
    def total(cls, start=None, end=None):
148
        r = DBSession.query(func.sum(cls.amount).label('a'))\
149
                        .join(event.Event)\
150
                        .filter(event.Event.deleted==False)
151
152
        if start:
153
            r = r.filter(event.Event.timestamp>=start)
154
        if end:
155
            r = r.filter(event.Event.timestamp<end)
156
157
        return r.one().a or Decimal(0.0)
158
159
    # Get the total amount of discounts people have received for keeping
160
    # money in their account
161 View Code Duplication
    @classmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
162
    def discounts(cls, start=None, end=None):
163
        r = DBSession.query(func.sum((cls.amount / (1-cls.discount)) - cls.amount).label('d'))\
164
                        .join(event.Event)\
165
                        .filter(cls.discount > 0)\
166
                        .filter(event.Event.deleted==False)
167
168
        if start:
169
            r = r.filter(event.Event.timestamp>=start)
170
        if end:
171
            r = r.filter(event.Event.timestamp<end)
172
173
        return r.one().d or Decimal(0.0)
174
175
    # Get the total amount of fees people have paid for being in debt
176 View Code Duplication
    @classmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
177
    def fees(cls, start=None, end=None):
178
        r = DBSession.query(func.sum((cls.amount / (1-cls.discount)) - cls.amount).label('f'))\
179
                        .join(event.Event)\
180
                        .filter(cls.discount < 0)\
181
                        .filter(event.Event.deleted==False)
182
183
        if start:
184
            r = r.filter(event.Event.timestamp>=start)
185
        if end:
186
            r = r.filter(event.Event.timestamp<end)
187
188
        return r.one().f or Decimal(0.0)
189
190
    # Returns an array of tuples where the first item is a millisecond timestamp,
191
    # the next is the total amount of debt, and the next is the total amount
192
    # of stored money for users.
193
    @classmethod
194
    def get_balance_total_daily(cls):
195
        rows = DBSession.query(cls.amount,
196
                               cls.type,
197
                               cls.to_account_virt_id,
198
                               cls.fr_account_virt_id,
199
                               event.Event.timestamp)\
200
                        .join(event.Event)\
201
                        .filter(event.Event.deleted==False)\
202
                        .filter(or_(
203
                                  cls.type=='purchase',
204
                                  cls.type=='cashdeposit',
205
                                  cls.type=='ccdeposit',
206
                                  cls.type=='btcdeposit',
207
                                  cls.type=='adjustment'
208
                                ))\
209
                        .order_by(event.Event.timestamp)\
210
                        .all()
211
        return utility.timeseries_balance_total_daily(rows)
212
213
214 View Code Duplication
    @classmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
215
    def get_transactions_over_time_for_user(cls, user):
216
        return DBSession.query(cls.amount,
217
                               cls.type,
218
                               cls.to_account_virt_id,
219
                               cls.fr_account_virt_id,
220
                               event.Event.timestamp)\
221
                        .join(event.Event)\
222
                        .filter(event.Event.deleted==False)\
223
                        .filter(or_(
224
                                  cls.type=='purchase',
225
                                  cls.type=='cashdeposit',
226
                                  cls.type=='ccdeposit',
227
                                  cls.type=='btcdeposit',
228
                                  cls.type=='adjustment'
229
                                ))\
230
                        .filter(or_(
231
                            cls.to_account_virt_id == user.id,
232
                            cls.fr_account_virt_id == user.id,
233
                            ))\
234
                        .order_by(event.Event.timestamp)\
235
                        .all()
236
237
238
    @classmethod
239
    def get_balances_over_time_for_user(cls, user):
240
        rows = cls.get_transactions_over_time_for_user(user)
241
        # We can re-use the global balance calculation code because the query
242
        # filtered it down to only this user, only now the "global" total
243
        # positive values (r[2]) and total debt (r[1]) are just this user's
244
        # balance, so we pull out the right column at each point in time.
245
        rows = utility.timeseries_balance_total_daily(rows)
246
        rows = [(r[0],r[2]/100 if r[1]==0 else -r[1]/100) for r in rows]
247
        return rows
248
249
    @classmethod
250
    def get_days_in_debt_for_user(cls, user):
251
        rows = cls.get_transactions_over_time_for_user(user)
252
        days = utility.get_days_on_shame(user, rows)
253
        return days
254
255
256 View Code Duplication
def __get_transactions_query(self):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
257
    return object_session(self).query(Transaction)\
258
            .join(event.Event)\
259
            .filter(or_(
260
                      or_(
261
                        Transaction.to_account_virt_id == self.id,
262
                        Transaction.fr_account_virt_id == self.id,
263
                        Transaction.to_account_cash_id == self.id,
264
                        Transaction.fr_account_cash_id == self.id),
265
                      and_(
266
                        or_(event.Event.type == "purchase",
267
                            event.Event.type == "deposit"),
268
                        event.Event.user_id == self.id)))\
269
            .filter(event.Event.deleted==False)\
270
            .order_by(desc(event.Event.timestamp))\
271
272
@limitable_all
273
def __get_transactions(self):
274
    return __get_transactions_query(self)
275
276
@property
277
def __transactions(self):
278
    return __get_transactions(self)
279
280
account.Account.get_transactions_query = __get_transactions_query
281
account.Account.get_transactions = __get_transactions
282
account.Account.transactions = __transactions
283
284
# This is in a stupid place due to circular input problems
285 View Code Duplication
@limitable_all
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
286
def __get_events(self):
287
    return object_session(self).query(event.Event)\
288
            .join(Transaction)\
289
            .filter(or_(
290
                      or_(
291
                        Transaction.to_account_virt_id == self.id,
292
                        Transaction.fr_account_virt_id == self.id,
293
                        Transaction.to_account_cash_id == self.id,
294
                        Transaction.fr_account_cash_id == self.id),
295
                      and_(
296
                        or_(event.Event.type == "purchase",
297
                            event.Event.type == "deposit"),
298
                        event.Event.user_id == self.id)))\
299
            .filter(event.Event.deleted==False)\
300
            .order_by(desc(event.Event.timestamp))
301
302
@property
303
def __events(self):
304
    return __get_events(self).all()
305
306
account.Account.get_events = __get_events
307
account.Account.events = __events
308
309
# This is in a stupid place due to circular input problems
310
@property
311
def __total_deposit_amount(self):
312
    return object_session(self).query(func.sum(Transaction.amount).label("total"))\
313
            .join(event.Event)\
314
            .filter(and_(
315
                        Transaction.to_account_virt_id == self.id,
316
                        or_(Transaction.type == 'cashdeposit',
317
                            Transaction.type == 'ccdeposit',
318
                            Transaction.type == 'btcdeposit')))\
319
            .filter(event.Event.deleted==False).one().total or Decimal(0.0)
320
account.Account.total_deposits = __total_deposit_amount
321
322
# This is in a stupid place due to circular input problems
323
@property
324
def __total_purchase_amount(self):
325
    return object_session(self).query(func.sum(Transaction.amount).label("total"))\
326
            .join(event.Event)\
327
            .filter(and_(
328
                        Transaction.fr_account_virt_id == self.id,
329
                        Transaction.type == 'purchase'))\
330
            .filter(event.Event.deleted==False).one().total or Decimal(0.0)
331
account.Account.total_purchases = __total_purchase_amount
332
333
# This is in a stupid place due to circular input problems
334
@classmethod
335
@limitable_all
336
def __get_cash_events(cls):
337
    return DBSession.query(event.Event)\
338
            .join(Transaction)\
339
            .filter(or_(
340
                      Transaction.to_account_cash_id == account.get_cash_account("chezbetty").id,
341
                      Transaction.fr_account_cash_id == account.get_cash_account("chezbetty").id))\
342
            .filter(event.Event.deleted==False)\
343
            .order_by(desc(event.Event.timestamp))
344
event.Event.get_cash_events = __get_cash_events
345
346
# This is in a stupid place due to circular input problems
347
@classmethod
348
@limitable_all
349
def __get_restock_events(cls):
350
    return DBSession.query(event.Event)\
351
            .join(Transaction)\
352
            .filter(Transaction.type == 'restock')\
353
            .filter(event.Event.deleted==False)\
354
            .order_by(desc(event.Event.timestamp))
355
event.Event.get_restock_events = __get_restock_events
356
357
# This is in a stupid place due to circular input problems
358
@classmethod
359
@limitable_all
360
def __get_emptycash_events(cls):
361
    return DBSession.query(event.Event)\
362
            .join(Transaction)\
363
            .filter(or_(
364
                      Transaction.type == 'emptycashbox',
365
                      Transaction.type == 'emptysafe',
366
                      Transaction.type == 'emptybitcoin'))\
367
            .filter(event.Event.deleted==False)\
368
            .order_by(desc(event.Event.timestamp))
369
event.Event.get_emptycash_events = __get_emptycash_events
370
371
# This is in a stupid place due to circular input problems
372
@classmethod
373
@limitable_all
374
def __get_deposit_events(cls):
375
    return DBSession.query(event.Event)\
376
            .join(Transaction)\
377
            .filter(or_(
378
                      Transaction.type == 'cashdeposit',
379
                      Transaction.type == 'ccdeposit',
380
                      Transaction.type == 'btcdeposit'))\
381
            .filter(event.Event.deleted==False)\
382
            .order_by(desc(event.Event.timestamp))
383
event.Event.get_deposit_events = __get_deposit_events
384
385
# This is in a stupid place due to circular input problems
386
@classmethod
387
@limitable_all
388
def __get_donation_events(cls):
389
    return DBSession.query(event.Event)\
390
            .join(Transaction)\
391
            .filter(or_(
392
                      Transaction.type == 'donation',
393
                      Transaction.type == 'withdrawal'))\
394
            .filter(event.Event.deleted==False)\
395
            .order_by(desc(event.Event.timestamp))
396
event.Event.get_donation_events = __get_donation_events
397
398
# This is in a stupid place due to circular input problems
399
@classmethod
400
def __get_deadbeats(cls):
401
    deadbeats = DBSession.query(user.User)\
402
            .filter(user.User.enabled==True)\
403
            .filter(user.User.archived==False)\
404
            .filter(user.User.balance <= -5)\
405
            .all()
406
407
    # Only get users between 0 and -5 if they have been in debt for a week or
408
    # more.
409
    iffy_users = DBSession.query(user.User)\
410
            .filter(user.User.enabled==True)\
411
            .filter(user.User.archived==False)\
412
            .filter(user.User.balance < 0)\
413
            .filter(user.User.balance > -5)\
414
            .all()
415
    for u in iffy_users:
416
        days = Transaction.get_days_in_debt_for_user(u)
417
        if days >= 7:
418
            deadbeats.append(u)
419
420
    return deadbeats
421
user.User.get_deadbeats = __get_deadbeats
422
423
# This is in a stupid place due to circular input problems
424 View Code Duplication
@property
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
425
def __days_since_last_purchase(self):
426
    last_purchase = object_session(self).query(event.Event)\
427
            .join(Transaction)\
428
            .filter(Transaction.fr_account_virt_id == self.id)\
429
            .filter(event.Event.type == 'purchase')\
430
            .filter(event.Event.deleted==False)\
431
            .order_by(desc(event.Event.timestamp)).first()
432
433
    if last_purchase:
434
        diff = arrow.now() - last_purchase.timestamp
435
        return diff.days
436
    else:
437
        return None
438
user.User.days_since_last_purchase = __days_since_last_purchase
439
440
# This is in a stupid place due to circular input problems
441 View Code Duplication
@property
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
442
def __lifetime_fees(self):
443
    return object_session(self).query(func.sum((Purchase.amount / (1-Purchase.discount)) - Purchase.amount).label("f"))\
444
            .join(event.Event)\
445
            .filter(Purchase.fr_account_virt_id == self.id)\
446
            .filter(Purchase.discount < 0)\
447
            .filter(event.Event.type == 'purchase')\
448
            .filter(event.Event.deleted==False).one().f or Decimal(0.0)
449
user.User.lifetime_fees = __lifetime_fees
450
451
# This is in a stupid place due to circular input problems
452 View Code Duplication
@property
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
453
def __lifetime_discounts(self):
454
    return object_session(self).query(func.sum((Purchase.amount / (1-Purchase.discount)) - Purchase.amount).label("f"))\
455
            .join(event.Event)\
456
            .filter(Purchase.fr_account_virt_id == self.id)\
457
            .filter(Purchase.discount > 0)\
458
            .filter(event.Event.type == 'purchase')\
459
            .filter(event.Event.deleted==False).one().f or Decimal(0.0)
460
user.User.lifetime_discounts = __lifetime_discounts
461
462
463
464
################################################################################
465
## Related Classes
466
################################################################################
467
468
class Purchase(Transaction):
469
    __mapper_args__ = {'polymorphic_identity': 'purchase'}
470
    discount = Column(Numeric)
471
472
    def __init__(self, event, user, discount=None):
473
        chezbetty_v = account.get_virt_account("chezbetty")
474
        Transaction.__init__(self, event, user, chezbetty_v, None, None, Decimal(0.0))
475
        self.discount = discount
476
477
478
class Deposit(Transaction):
479
    __mapper_args__ = {'polymorphic_identity': 'deposit'}
480
481 View Code Duplication
    @classmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
482
    def deposits_by_period(cls, period, start=None, end=None):
483
        r = DBSession.query(cls.amount.label('summable'), event.Event.timestamp)\
484
                     .join(event.Event)\
485
                     .order_by(event.Event.timestamp)\
486
                     .filter(event.Event.deleted==False)
487
        if start:
488
            r = r.filter(event.Event.timestamp>=start.replace(tzinfo=None))
489
        if end:
490
            r = r.filter(event.Event.timestamp<end.replace(tzinfo=None))
491
492
        return utility.group(r.all(), period)
493
494
495
class CashDeposit(Deposit):
496
    __mapper_args__ = {'polymorphic_identity': 'cashdeposit'}
497
498
    CONTENTS_THRESHOLD = 1000
499
    REPEAT_THRESHOLD = 100
500
501
    def __init__(self, event, user, amount):
502
        cashbox_c = account.get_cash_account("cashbox")
503
        prev = cashbox_c.balance
504
        Transaction.__init__(self, event, None, user, None, cashbox_c, amount)
505
        new = cashbox_c.balance
506
507
        # It feels like the model should not have all of this application
508
        # specific logic in it. What does sending an email have to do with
509
        # representing a transaction. I think this should be moved to
510
        # datalayer.py which does handle application logic.
511
        try:
512
            if prev < CashDeposit.CONTENTS_THRESHOLD and new > CashDeposit.CONTENTS_THRESHOLD:
513
                self.send_alert_email(new)
514
            elif prev > CashDeposit.CONTENTS_THRESHOLD:
515
                pr = int((prev - CashDeposit.CONTENTS_THRESHOLD) / CashDeposit.REPEAT_THRESHOLD)
516
                nr = int((new - CashDeposit.CONTENTS_THRESHOLD) / CashDeposit.REPEAT_THRESHOLD)
517
                if pr != nr:
518
                    self.send_alert_email(new, nr)
519
        except:
520
            # Some error sending email. Let's not prevent the deposit from
521
            # going through.
522
            pass
523
524
    def send_alert_email(self, amount, repeat=0):
525
        settings = get_current_registry().settings
526
527
        SUBJECT = 'Time to empty Betty. Cash box has ${}.'.format(amount)
528
        TO = '[email protected]'
529
530
        body = """
531
        <p>Betty's cash box is getting full. Time to go to the bank.</p>
532
        <p>The cash box currently contains ${}.</p>
533
        """.format(amount)
534
        if repeat > 8:
535
            body = """
536
            <p><strong>Yo! Get your shit together! That's a lot of cash lying
537
            around!</strong></p>""" + body
538
        elif repeat > 4:
539
            body = body + """
540
            <p><strong>But seriously, you should probably go empty the cashbox
541
            like, right meow.</strong></p>"""
542
543
        if 'debugging' in settings and bool(int(settings['debugging'])):
544
            SUBJECT = '[ DEBUG_MODE ] ' + SUBJECT
545
            body = """
546
            <p><em>This message was sent from a debugging session and may be
547
            safely ignored.</em></p>""" + body
548
549
        utility.send_email(TO=TO, SUBJECT=SUBJECT, body=body)
550
551
552
class CCDeposit(Deposit):
553
    __mapper_args__ = {'polymorphic_identity': 'ccdeposit'}
554
555
    stripe_id = Column(Text)
556
    cc_last4 = Column(Text)
557
558
    def __init__(self, event, user, amount, stripe_id, last4):
559
        chezbetty_c = account.get_cash_account("chezbetty")
560
        Transaction.__init__(self, event, None, user, None, chezbetty_c, amount)
561
        self.stripe_id = stripe_id
562
        self.cc_last4 = last4
563
564
565
class BTCDeposit(Deposit):
566
    __mapper_args__ = {'polymorphic_identity': 'btcdeposit'}
567
568
    btctransaction = Column(String(64))
569
    address        = Column(String(64))
570
    amount_btc     = Column(Numeric, nullable=True)
571
572
    def __init__(self, event, user, amount, btctransaction, address, amount_btc):
573
        btcbox_c = account.get_cash_account("btcbox")
574
        Transaction.__init__(self, event, None, user, None, btcbox_c, amount)
575
        self.btctransaction = btctransaction
576
        self.address = address
577
        self.amount_btc = amount_btc
578
579
    def __getattr__(self, name):
580
        if name == 'img':
581
            return utility.string_to_qrcode(self.btctransaction)
582
        else:
583
            raise AttributeError
584
585
    @classmethod
586
    def from_address(cls, address):
587
        return DBSession.query(cls).join(event.Event)\
588
                        .filter(cls.address == address)\
589
                        .filter(event.Event.deleted == False).one()
590
591
592
class Adjustment(Transaction):
593
    __mapper_args__ = {'polymorphic_identity': 'adjustment'}
594
595
    def __init__(self, event, user, amount):
596
        chezbetty_v = account.get_virt_account("chezbetty")
597
        Transaction.__init__(self, event, chezbetty_v, user, None, None, amount)
598
599
600
class Restock(Transaction):
601
    __mapper_args__ = {'polymorphic_identity': 'restock'}
602
603
    # Additional cost that should get distributed over the entire restock
604
    amount_restock_cost = Column(Numeric, nullable=True)
605
606
    def __init__(self, event, global_cost):
607
        chezbetty_v = account.get_virt_account("chezbetty")
608
        chezbetty_c = account.get_cash_account("chezbetty")
609
        Transaction.__init__(self, event, chezbetty_v, None, chezbetty_c, None, Decimal(0.0))
610
        self.amount_restock_cost = global_cost
611
612
613
class Inventory(Transaction):
614
    __mapper_args__ = {'polymorphic_identity': 'inventory'}
615
    def __init__(self, event):
616
        chezbetty_v = account.get_virt_account("chezbetty")
617
        Transaction.__init__(self, event, chezbetty_v, None, None, None, Decimal(0.0))
618
619
620
class EmptyCashBox(Transaction):
621
    __mapper_args__ = {'polymorphic_identity': 'emptycashbox'}
622
    def __init__(self, event):
623
        cashbox_c = account.get_cash_account("cashbox")
624
        amount = cashbox_c.balance
625
        safe_c = account.get_cash_account("safe")
626
        Transaction.__init__(self, event, None, None, cashbox_c, safe_c, amount)
627
628
629
class EmptySafe(Transaction):
630
    __mapper_args__ = {'polymorphic_identity': 'emptysafe'}
631
    def __init__(self, event, amount):
632
        safe_c = account.get_cash_account("safe")
633
        chezbetty_c = account.get_cash_account("chezbetty")
634
        Transaction.__init__(self, event, None, None, safe_c, chezbetty_c, amount)
635
636
637
class EmptyBitcoin(Transaction):
638
    __mapper_args__ = {'polymorphic_identity': 'emptybitcoin'}
639
    def __init__(self, event, amount):
640
        btnbox_c = account.get_cash_account("btcbox")
641
        chezbetty_c = account.get_cash_account("chezbetty")
642
        Transaction.__init__(self, event, None, None, btnbox_c, chezbetty_c, amount)
643
644
645
class Lost(Transaction):
646
    __mapper_args__ = {'polymorphic_identity': 'lost'}
647
    def __init__(self, event, source_acct, amount):
648
        Transaction.__init__(self, event, None, None, source_acct, None, amount)
649
650
651
class Found(Transaction):
652
    __mapper_args__ = {'polymorphic_identity': 'found'}
653
    def __init__(self, event, dest_acct, amount):
654
        Transaction.__init__(self, event, None, None, None, dest_acct, amount)
655
656
657
class Donation(Transaction):
658
    __mapper_args__ = {'polymorphic_identity': 'donation'}
659
    def __init__(self, event, amount):
660
        chezbetty_v = account.get_virt_account("chezbetty")
661
        chezbetty_c = account.get_cash_account("chezbetty")
662
        Transaction.__init__(self, event, None, chezbetty_v, None, chezbetty_c, amount)
663
664
665
class Withdrawal(Transaction):
666
    __mapper_args__ = {'polymorphic_identity': 'withdrawal'}
667
    def __init__(self, event, amount):
668
        chezbetty_v = account.get_virt_account("chezbetty")
669
        chezbetty_c = account.get_cash_account("chezbetty")
670
        Transaction.__init__(self, event, chezbetty_v, None, chezbetty_c, None, amount)
671
672
673
################################################################################
674
## SUB TRANSACTIONS
675
################################################################################
676
677
class SubTransaction(Base):
678
    __tablename__   = "subtransactions"
679
680
    id              = Column(Integer, primary_key=True, nullable=False)
681
    transaction_id  = Column(Integer, ForeignKey("transactions.id"), nullable=False)
682
    amount          = Column(Numeric, nullable=False)
683
    type            = Column(Enum("purchaselineitem", "restocklineitem",
684
                                  "restocklinebox", "inventorylineitem",
685
                                  name="subtransaction_type"), nullable=False)
686
    item_id         = Column(Integer, ForeignKey("items.id"), nullable=True)
687
    quantity        = Column(Integer, nullable=False)
688
    wholesale       = Column(Numeric, nullable=False)
689
690
    # For restocks
691
    coupon_amount   = Column(Numeric, nullable=True) # Amount of discount on the item
692
    sales_tax       = Column(Boolean, nullable=True) # Whether sales tax was charged
693
    bottle_deposit  = Column(Boolean, nullable=True) # Whether there was a bottle deposit
694
695
    transaction     = relationship(Transaction, backref="subtransactions", cascade="all")
696
    item            = relationship(item.Item, backref="subtransactions")
697
698
    __mapper_args__ = {'polymorphic_on': type}
699
700
    def __init__(self, transaction, amount, item_id, quantity, wholesale):
701
        self.transaction_id = transaction.id
702
        self.amount = amount
703
        self.item_id = item_id
704
        self.quantity = quantity
705
        self.wholesale = wholesale
706
707
    def __getattr__(self, name):
708
        if name == 'deleted':
709
            return self.transaction.event.deleted
710
        else:
711
            raise AttributeError
712
713
    @classmethod
714
    @limitable_all
715
    def all_item(cls, id):
716
        return DBSession.query(cls)\
717
                        .join(Transaction)\
718
                        .join(event.Event)\
719
                        .filter(cls.item_id == id)\
720
                        .filter(event.Event.deleted==False)\
721
                        .order_by(desc(event.Event.timestamp))
722
723
    @classmethod
724
    @limitable_all
725
    def all_item_purchases(cls, id):
726
        return DBSession.query(cls)\
727
                        .join(Transaction)\
728
                        .join(event.Event)\
729
                        .filter(cls.item_id == id)\
730
                        .filter(event.Event.deleted==False)\
731
                        .filter(event.Event.type=="purchase")\
732
                        .order_by(desc(event.Event.timestamp))
733
734
    @classmethod
735
    @limitable_all
736
    def all_item_events(cls, id):
737
        return DBSession.query(cls)\
738
                        .join(Transaction)\
739
                        .join(event.Event)\
740
                        .filter(cls.item_id == id)\
741
                        .filter(event.Event.deleted==False)\
742
                        .filter(or_(event.Event.type=="inventory", event.Event.type =="restock"))\
743
                        .order_by(desc(event.Event.timestamp))
744
745 View Code Duplication
    @classmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
746
    @limitable_all
747
    def all(cls, trans_type=None):
748
        if not trans_type:
749
            return DBSession.query(cls)\
750
                            .join(Transaction)\
751
                            .join(event.Event)\
752
                            .filter(event.Event.deleted==False)\
753
                            .order_by(desc(event.Event.timestamp))
754
        else:
755
            return DBSession.query(cls)\
756
                            .join(Transaction)\
757
                            .join(event.Event)\
758
                            .filter(cls.type==trans_type)\
759
                            .filter(event.Event.deleted==False)\
760
                            .order_by(desc(event.Event.timestamp))
761
762
class PurchaseLineItem(SubTransaction):
763
    __mapper_args__ = {'polymorphic_identity': 'purchaselineitem'}
764
    price           = Column(Numeric)
765
    def __init__(self, transaction, amount, item, quantity, price, wholesale):
766
        SubTransaction.__init__(self, transaction, amount, item.id, quantity, wholesale)
767
        self.price = price
768
769 View Code Duplication
    @classmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
770
    def quantity_by_period(cls, period, start=None, end=None):
771
        r = DBSession.query(cls.quantity.label('summable'), event.Event.timestamp)\
772
                     .join(Transaction)\
773
                     .join(event.Event)\
774
                     .filter(event.Event.deleted==False)\
775
                     .order_by(event.Event.timestamp)
776
        if start:
777
            r = r.filter(event.Event.timestamp>=start.replace(tzinfo=None))
778
        if end:
779
            r = r.filter(event.Event.timestamp<end.replace(tzinfo=None))
780
        return utility.group(r.all(), period)
781
782 View Code Duplication
    @classmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
783
    def virtual_revenue_by_period(cls, period, start=None, end=None):
784
        r = DBSession.query(cls.amount.label('summable'), event.Event.timestamp)\
785
                     .join(Transaction)\
786
                     .join(event.Event)\
787
                     .filter(event.Event.deleted==False)\
788
                     .order_by(event.Event.timestamp)
789
        if start:
790
            r = r.filter(event.Event.timestamp>=start.replace(tzinfo=None))
791
        if end:
792
            r = r.filter(event.Event.timestamp<end.replace(tzinfo=None))
793
        return utility.group(r.all(), period)
794
795 View Code Duplication
    @classmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
796
    def profit_on_sales(cls, start=None, end=None):
797
        r = DBSession.query(func.sum(cls.amount-(cls.wholesale*cls.quantity)).label('p'))\
798
                        .join(Transaction)\
799
                        .join(event.Event)\
800
                        .filter(event.Event.deleted==False)
801
        if start:
802
            r = r.filter(event.Event.timestamp>=start.replace(tzinfo=None))
803
        if end:
804
            r = r.filter(event.Event.timestamp<end.replace(tzinfo=None))
805
806
        return r.one().p or Decimal(0.0)
807
808
    @classmethod
809
    def item_sale_quantities(cls, item_id):
810
        return DBSession.query(cls, event.Event)\
811
                        .join(Transaction)\
812
                        .join(event.Event)\
813
                        .filter(event.Event.deleted==False)\
814
                        .filter(cls.item_id==int(item_id))\
815
                        .order_by(event.Event.timestamp).all()
816
817
818
# This is slowww:
819
# @property
820
# def __number_sold(self):
821
#     return object_session(self).query(func.sum(PurchaseLineItem.quantity).label('c'))\
822
#                                .join(Transaction)\
823
#                                .join(event.Event)\
824
#                                .filter(PurchaseLineItem.item_id==self.id)\
825
#                                .filter(event.Event.deleted==False).one().c
826
# item.Item.number_sold = __number_sold
827
828
829
class RestockLineItem(SubTransaction):
830
    __mapper_args__ = {'polymorphic_identity': 'restocklineitem'}
831
    def __init__(self,
832
                 transaction,
833
                 amount,
834
                 item,
835
                 quantity,
836
                 wholesale,
837
                 coupon,
838
                 sales_tax,
839
                 bottle_deposit):
840
        SubTransaction.__init__(self, transaction, amount, item.id, quantity, wholesale)
841
        self.coupon_amount = coupon
842
        self.sales_tax = sales_tax
843
        self.bottle_deposit = bottle_deposit
844
845
846
class RestockLineBox(SubTransaction):
847
    __mapper_args__ = {'polymorphic_identity': 'restocklinebox'}
848
    box_id          = Column(Integer, ForeignKey("boxes.id"), nullable=True)
849
850
    box             = relationship(box.Box, backref="subtransactions")
851
852
    def __init__(self,
853
                 transaction,
854
                 amount,
855
                 box,
856
                 quantity,
857
                 wholesale,
858
                 coupon,
859
                 sales_tax,
860
                 bottle_deposit):
861
        self.transaction_id = transaction.id
862
        self.amount = amount
863
        self.box_id = box.id
864
        self.quantity = quantity
865
        self.wholesale = wholesale
866
        self.coupon_amount = coupon
867
        self.sales_tax = sales_tax
868
        self.bottle_deposit = bottle_deposit
869
870
871
class InventoryLineItem(SubTransaction):
872
    __mapper_args__    = {'polymorphic_identity': 'inventorylineitem'}
873
    quantity_predicted = synonym(SubTransaction.quantity)
874
    quantity_counted   = Column(Integer)
875
876
    def __init__(self, transaction, amount, item, quantity_predicted, quantity_counted, wholesale):
877
        SubTransaction.__init__(self, transaction, amount, item.id, quantity_predicted, wholesale)
878
        self.quantity_counted = quantity_counted
879
880
881
882
################################################################################
883
## SUBSUB TRANSACTIONS
884
################################################################################
885
886
# This is for tracking which items were in which boxes when we restocked
887
888
class SubSubTransaction(Base):
889
    __tablename__      = "subsubtransactions"
890
891
    id                 = Column(Integer, primary_key=True, nullable=False)
892
    subtransaction_id  = Column(Integer, ForeignKey("subtransactions.id"), nullable=False)
893
    type               = Column(Enum("restocklineboxitem",
894
                                     name="subsubtransaction_type"), nullable=False)
895
    item_id            = Column(Integer, ForeignKey("items.id"), nullable=True)
896
    quantity           = Column(Integer, nullable=False)
897
898
    subtransaction     = relationship(SubTransaction, backref="subsubtransactions", cascade="all")
899
    item               = relationship(item.Item, backref="subsubtransactions")
900
901
    __mapper_args__    = {'polymorphic_on': type}
902
903
    def __init__(self, subtransaction, item_id, quantity):
904
        self.subtransaction_id = subtransaction.id
905
        self.item_id = item_id
906
        self.quantity = quantity
907
908
    def __getattr__(self, name):
909
        if name == 'deleted':
910
            return self.subtransaction.transaction.event.deleted
911
        else:
912
            raise AttributeError
913
914
    @classmethod
915
    @limitable_all
916
    def all_item(cls, item_id):
917
        return DBSession.query(cls)\
918
                        .join(SubTransaction)\
919
                        .join(Transaction)\
920
                        .join(event.Event)\
921
                        .filter(cls.item_id == item_id)\
922
                        .filter(event.Event.deleted==False)\
923
                        .order_by(cls.id)
924
925
926
class RestockLineBoxItem(SubSubTransaction):
927
    __mapper_args__ = {'polymorphic_identity': 'restocklineboxitem'}
928
    def __init__(self, subtransaction, item, quantity):
929
        SubSubTransaction.__init__(self, subtransaction, item.id, quantity)
930
931
932
933