Completed
Push — master ( e20fcc...6f9fcb )
by
unknown
58s
created

chezbetty.models.__get_deadbeats()   A

Complexity

Conditions 3

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 3
dl 0
loc 22
rs 9.2
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
    @classmethod
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
    @classmethod
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
    @classmethod
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
def __get_transactions_query(self):
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
@limitable_all
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
def __get_deadbeats(cls):
388
    deadbeats = DBSession.query(user.User)\
389
            .filter(user.User.enabled==True)\
390
            .filter(user.User.archived==False)\
391
            .filter(user.User.balance <= -5)\
392
            .all()
393
394
    # Only get users between 0 and -5 if they have been in debt for a week or
395
    # more.
396
    iffy_users = DBSession.query(user.User)\
397
            .filter(user.User.enabled==True)\
398
            .filter(user.User.archived==False)\
399
            .filter(user.User.balance < 0)\
400
            .filter(user.User.balance > -5)\
401
            .all()
402
    for u in iffy_users:
403
        days = Transaction.get_days_in_debt_for_user(u)
404
        if days >= 7:
405
            deadbeats.append(u)
406
407
    return deadbeats
408
user.User.get_deadbeats = __get_deadbeats
409
410
# This is in a stupid place due to circular input problems
411
@property
412
def __days_since_last_purchase(self):
413
    last_purchase = object_session(self).query(event.Event)\
414
            .join(Transaction)\
415
            .filter(Transaction.fr_account_virt_id == self.id)\
416
            .filter(event.Event.type == 'purchase')\
417
            .filter(event.Event.deleted==False)\
418
            .order_by(desc(event.Event.timestamp)).first()
419
420
    if last_purchase:
421
        diff = arrow.now() - last_purchase.timestamp
422
        return diff.days
423
    else:
424
        return None
425
user.User.days_since_last_purchase = __days_since_last_purchase
426
427
# This is in a stupid place due to circular input problems
428
@property
429
def __lifetime_fees(self):
430
    return object_session(self).query(func.sum((Purchase.amount / (1-Purchase.discount)) - Purchase.amount).label("f"))\
431
            .join(event.Event)\
432
            .filter(Purchase.fr_account_virt_id == self.id)\
433
            .filter(Purchase.discount < 0)\
434
            .filter(event.Event.type == 'purchase')\
435
            .filter(event.Event.deleted==False).one().f or Decimal(0.0)
436
user.User.lifetime_fees = __lifetime_fees
437
438
# This is in a stupid place due to circular input problems
439
@property
440
def __lifetime_discounts(self):
441
    return object_session(self).query(func.sum((Purchase.amount / (1-Purchase.discount)) - Purchase.amount).label("f"))\
442
            .join(event.Event)\
443
            .filter(Purchase.fr_account_virt_id == self.id)\
444
            .filter(Purchase.discount > 0)\
445
            .filter(event.Event.type == 'purchase')\
446
            .filter(event.Event.deleted==False).one().f or Decimal(0.0)
447
user.User.lifetime_discounts = __lifetime_discounts
448
449
450
451
################################################################################
452
## Related Classes
453
################################################################################
454
455
class Purchase(Transaction):
456
    __mapper_args__ = {'polymorphic_identity': 'purchase'}
457
    discount = Column(Numeric)
458
459
    def __init__(self, event, user, discount=None):
460
        chezbetty_v = account.get_virt_account("chezbetty")
461
        Transaction.__init__(self, event, user, chezbetty_v, None, None, Decimal(0.0))
462
        self.discount = discount
463
464
465
class Deposit(Transaction):
466
    __mapper_args__ = {'polymorphic_identity': 'deposit'}
467
468
    @classmethod
469
    def deposits_by_period(cls, period, start=None, end=None):
470
        r = DBSession.query(cls.amount.label('summable'), event.Event.timestamp)\
471
                     .join(event.Event)\
472
                     .order_by(event.Event.timestamp)\
473
                     .filter(event.Event.deleted==False)
474
        if start:
475
            r = r.filter(event.Event.timestamp>=start.replace(tzinfo=None))
476
        if end:
477
            r = r.filter(event.Event.timestamp<end.replace(tzinfo=None))
478
479
        return utility.group(r.all(), period)
480
481
482
class CashDeposit(Deposit):
483
    __mapper_args__ = {'polymorphic_identity': 'cashdeposit'}
484
485
    CONTENTS_THRESHOLD = 1000
486
    REPEAT_THRESHOLD = 100
487
488
    def __init__(self, event, user, amount):
489
        cashbox_c = account.get_cash_account("cashbox")
490
        prev = cashbox_c.balance
491
        Transaction.__init__(self, event, None, user, None, cashbox_c, amount)
492
        new = cashbox_c.balance
493
494
        # It feels like the model should not have all of this application
495
        # specific logic in it. What does sending an email have to do with
496
        # representing a transaction. I think this should be moved to
497
        # datalayer.py which does handle application logic.
498
        try:
499
            if prev < CashDeposit.CONTENTS_THRESHOLD and new > CashDeposit.CONTENTS_THRESHOLD:
500
                self.send_alert_email(new)
501
            elif prev > CashDeposit.CONTENTS_THRESHOLD:
502
                pr = int((prev - CashDeposit.CONTENTS_THRESHOLD) / CashDeposit.REPEAT_THRESHOLD)
503
                nr = int((new - CashDeposit.CONTENTS_THRESHOLD) / CashDeposit.REPEAT_THRESHOLD)
504
                if pr != nr:
505
                    self.send_alert_email(new, nr)
506
        except:
507
            # Some error sending email. Let's not prevent the deposit from
508
            # going through.
509
            pass
510
511
    def send_alert_email(self, amount, repeat=0):
512
        settings = get_current_registry().settings
513
514
        SUBJECT = 'Time to empty Betty. Cash box has ${}.'.format(amount)
515
        TO = '[email protected]'
516
517
        body = """
518
        <p>Betty's cash box is getting full. Time to go to the bank.</p>
519
        <p>The cash box currently contains ${}.</p>
520
        """.format(amount)
521
        if repeat > 8:
522
            body = """
523
            <p><strong>Yo! Get your shit together! That's a lot of cash lying
524
            around!</strong></p>""" + body
525
        elif repeat > 4:
526
            body = body + """
527
            <p><strong>But seriously, you should probably go empty the cashbox
528
            like, right meow.</strong></p>"""
529
530
        if 'debugging' in settings and bool(int(settings['debugging'])):
531
            SUBJECT = '[ DEBUG_MODE ] ' + SUBJECT
532
            body = """
533
            <p><em>This message was sent from a debugging session and may be
534
            safely ignored.</em></p>""" + body
535
536
        utility.send_email(TO=TO, SUBJECT=SUBJECT, body=body)
537
538
539
class CCDeposit(Deposit):
540
    __mapper_args__ = {'polymorphic_identity': 'ccdeposit'}
541
542
    stripe_id = Column(Text)
543
    cc_last4 = Column(Text)
544
545
    def __init__(self, event, user, amount, stripe_id, last4):
546
        chezbetty_c = account.get_cash_account("chezbetty")
547
        Transaction.__init__(self, event, None, user, None, chezbetty_c, amount)
548
        self.stripe_id = stripe_id
549
        self.cc_last4 = last4
550
551
552
class BTCDeposit(Deposit):
553
    __mapper_args__ = {'polymorphic_identity': 'btcdeposit'}
554
555
    btctransaction = Column(String(64))
556
    address        = Column(String(64))
557
    amount_btc     = Column(Numeric, nullable=True)
558
559
    def __init__(self, event, user, amount, btctransaction, address, amount_btc):
560
        btcbox_c = account.get_cash_account("btcbox")
561
        Transaction.__init__(self, event, None, user, None, btcbox_c, amount)
562
        self.btctransaction = btctransaction
563
        self.address = address
564
        self.amount_btc = amount_btc
565
566
    def __getattr__(self, name):
567
        if name == 'img':
568
            return utility.string_to_qrcode(self.btctransaction)
569
        else:
570
            raise AttributeError
571
572
    @classmethod
573
    def from_address(cls, address):
574
        return DBSession.query(cls).join(event.Event)\
575
                        .filter(cls.address == address)\
576
                        .filter(event.Event.deleted == False).one()
577
578
579
class Adjustment(Transaction):
580
    __mapper_args__ = {'polymorphic_identity': 'adjustment'}
581
582
    def __init__(self, event, user, amount):
583
        chezbetty_v = account.get_virt_account("chezbetty")
584
        Transaction.__init__(self, event, chezbetty_v, user, None, None, amount)
585
586
587
class Restock(Transaction):
588
    __mapper_args__ = {'polymorphic_identity': 'restock'}
589
590
    # Additional cost that should get distributed over the entire restock
591
    amount_restock_cost = Column(Numeric, nullable=True)
592
593
    def __init__(self, event, global_cost):
594
        chezbetty_v = account.get_virt_account("chezbetty")
595
        chezbetty_c = account.get_cash_account("chezbetty")
596
        Transaction.__init__(self, event, chezbetty_v, None, chezbetty_c, None, Decimal(0.0))
597
        self.amount_restock_cost = global_cost
598
599
600
class Inventory(Transaction):
601
    __mapper_args__ = {'polymorphic_identity': 'inventory'}
602
    def __init__(self, event):
603
        chezbetty_v = account.get_virt_account("chezbetty")
604
        Transaction.__init__(self, event, chezbetty_v, None, None, None, Decimal(0.0))
605
606
607
class EmptyCashBox(Transaction):
608
    __mapper_args__ = {'polymorphic_identity': 'emptycashbox'}
609
    def __init__(self, event):
610
        cashbox_c = account.get_cash_account("cashbox")
611
        amount = cashbox_c.balance
612
        safe_c = account.get_cash_account("safe")
613
        Transaction.__init__(self, event, None, None, cashbox_c, safe_c, amount)
614
615
616
class EmptySafe(Transaction):
617
    __mapper_args__ = {'polymorphic_identity': 'emptysafe'}
618
    def __init__(self, event, amount):
619
        safe_c = account.get_cash_account("safe")
620
        chezbetty_c = account.get_cash_account("chezbetty")
621
        Transaction.__init__(self, event, None, None, safe_c, chezbetty_c, amount)
622
623
624
class EmptyBitcoin(Transaction):
625
    __mapper_args__ = {'polymorphic_identity': 'emptybitcoin'}
626
    def __init__(self, event, amount):
627
        btnbox_c = account.get_cash_account("btcbox")
628
        chezbetty_c = account.get_cash_account("chezbetty")
629
        Transaction.__init__(self, event, None, None, btnbox_c, chezbetty_c, amount)
630
631
632
class Lost(Transaction):
633
    __mapper_args__ = {'polymorphic_identity': 'lost'}
634
    def __init__(self, event, source_acct, amount):
635
        Transaction.__init__(self, event, None, None, source_acct, None, amount)
636
637
638
class Found(Transaction):
639
    __mapper_args__ = {'polymorphic_identity': 'found'}
640
    def __init__(self, event, dest_acct, amount):
641
        Transaction.__init__(self, event, None, None, None, dest_acct, amount)
642
643
644
class Donation(Transaction):
645
    __mapper_args__ = {'polymorphic_identity': 'donation'}
646
    def __init__(self, event, amount):
647
        chezbetty_v = account.get_virt_account("chezbetty")
648
        chezbetty_c = account.get_cash_account("chezbetty")
649
        Transaction.__init__(self, event, None, chezbetty_v, None, chezbetty_c, amount)
650
651
652
class Withdrawal(Transaction):
653
    __mapper_args__ = {'polymorphic_identity': 'withdrawal'}
654
    def __init__(self, event, amount):
655
        chezbetty_v = account.get_virt_account("chezbetty")
656
        chezbetty_c = account.get_cash_account("chezbetty")
657
        Transaction.__init__(self, event, chezbetty_v, None, chezbetty_c, None, amount)
658
659
660
################################################################################
661
## SUB TRANSACTIONS
662
################################################################################
663
664
class SubTransaction(Base):
665
    __tablename__   = "subtransactions"
666
667
    id              = Column(Integer, primary_key=True, nullable=False)
668
    transaction_id  = Column(Integer, ForeignKey("transactions.id"), nullable=False)
669
    amount          = Column(Numeric, nullable=False)
670
    type            = Column(Enum("purchaselineitem", "restocklineitem",
671
                                  "restocklinebox", "inventorylineitem",
672
                                  name="subtransaction_type"), nullable=False)
673
    item_id         = Column(Integer, ForeignKey("items.id"), nullable=True)
674
    quantity        = Column(Integer, nullable=False)
675
    wholesale       = Column(Numeric, nullable=False)
676
677
    # For restocks
678
    coupon_amount   = Column(Numeric, nullable=True) # Amount of discount on the item
679
    sales_tax       = Column(Boolean, nullable=True) # Whether sales tax was charged
680
    bottle_deposit  = Column(Boolean, nullable=True) # Whether there was a bottle deposit
681
682
    transaction     = relationship(Transaction, backref="subtransactions", cascade="all")
683
    item            = relationship(item.Item, backref="subtransactions")
684
685
    __mapper_args__ = {'polymorphic_on': type}
686
687
    def __init__(self, transaction, amount, item_id, quantity, wholesale):
688
        self.transaction_id = transaction.id
689
        self.amount = amount
690
        self.item_id = item_id
691
        self.quantity = quantity
692
        self.wholesale = wholesale
693
694
    def __getattr__(self, name):
695
        if name == 'deleted':
696
            return self.transaction.event.deleted
697
        else:
698
            raise AttributeError
699
700
    @classmethod
701
    @limitable_all
702
    def all_item(cls, id):
703
        return DBSession.query(cls)\
704
                        .join(Transaction)\
705
                        .join(event.Event)\
706
                        .filter(cls.item_id == id)\
707
                        .filter(event.Event.deleted==False)\
708
                        .order_by(desc(event.Event.timestamp))
709
710
    @classmethod
711
    @limitable_all
712
    def all_item_purchases(cls, id):
713
        return DBSession.query(cls)\
714
                        .join(Transaction)\
715
                        .join(event.Event)\
716
                        .filter(cls.item_id == id)\
717
                        .filter(event.Event.deleted==False)\
718
                        .filter(event.Event.type=="purchase")\
719
                        .order_by(desc(event.Event.timestamp))
720
721
    @classmethod
722
    @limitable_all
723
    def all_item_events(cls, id):
724
        return DBSession.query(cls)\
725
                        .join(Transaction)\
726
                        .join(event.Event)\
727
                        .filter(cls.item_id == id)\
728
                        .filter(event.Event.deleted==False)\
729
                        .filter(or_(event.Event.type=="inventory", event.Event.type =="restock"))\
730
                        .order_by(desc(event.Event.timestamp))
731
732
    @classmethod
733
    @limitable_all
734
    def all(cls, trans_type=None):
735
        if not trans_type:
736
            return DBSession.query(cls)\
737
                            .join(Transaction)\
738
                            .join(event.Event)\
739
                            .filter(event.Event.deleted==False)\
740
                            .order_by(desc(event.Event.timestamp))
741
        else:
742
            return DBSession.query(cls)\
743
                            .join(Transaction)\
744
                            .join(event.Event)\
745
                            .filter(cls.type==trans_type)\
746
                            .filter(event.Event.deleted==False)\
747
                            .order_by(desc(event.Event.timestamp))
748
749
class PurchaseLineItem(SubTransaction):
750
    __mapper_args__ = {'polymorphic_identity': 'purchaselineitem'}
751
    price           = Column(Numeric)
752
    def __init__(self, transaction, amount, item, quantity, price, wholesale):
753
        SubTransaction.__init__(self, transaction, amount, item.id, quantity, wholesale)
754
        self.price = price
755
756
    @classmethod
757
    def quantity_by_period(cls, period, start=None, end=None):
758
        r = DBSession.query(cls.quantity.label('summable'), event.Event.timestamp)\
759
                     .join(Transaction)\
760
                     .join(event.Event)\
761
                     .filter(event.Event.deleted==False)\
762
                     .order_by(event.Event.timestamp)
763
        if start:
764
            r = r.filter(event.Event.timestamp>=start.replace(tzinfo=None))
765
        if end:
766
            r = r.filter(event.Event.timestamp<end.replace(tzinfo=None))
767
        return utility.group(r.all(), period)
768
769
    @classmethod
770
    def virtual_revenue_by_period(cls, period, start=None, end=None):
771
        r = DBSession.query(cls.amount.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
    @classmethod
783
    def profit_on_sales(cls, start=None, end=None):
784
        r = DBSession.query(func.sum(cls.amount-(cls.wholesale*cls.quantity)).label('p'))\
785
                        .join(Transaction)\
786
                        .join(event.Event)\
787
                        .filter(event.Event.deleted==False)
788
        if start:
789
            r = r.filter(event.Event.timestamp>=start.replace(tzinfo=None))
790
        if end:
791
            r = r.filter(event.Event.timestamp<end.replace(tzinfo=None))
792
793
        return r.one().p or Decimal(0.0)
794
795
    @classmethod
796
    def item_sale_quantities(cls, item_id):
797
        return DBSession.query(cls, event.Event)\
798
                        .join(Transaction)\
799
                        .join(event.Event)\
800
                        .filter(event.Event.deleted==False)\
801
                        .filter(cls.item_id==int(item_id))\
802
                        .order_by(event.Event.timestamp).all()
803
804
805
# This is slowww:
806
# @property
807
# def __number_sold(self):
808
#     return object_session(self).query(func.sum(PurchaseLineItem.quantity).label('c'))\
809
#                                .join(Transaction)\
810
#                                .join(event.Event)\
811
#                                .filter(PurchaseLineItem.item_id==self.id)\
812
#                                .filter(event.Event.deleted==False).one().c
813
# item.Item.number_sold = __number_sold
814
815
816
class RestockLineItem(SubTransaction):
817
    __mapper_args__ = {'polymorphic_identity': 'restocklineitem'}
818
    def __init__(self,
819
                 transaction,
820
                 amount,
821
                 item,
822
                 quantity,
823
                 wholesale,
824
                 coupon,
825
                 sales_tax,
826
                 bottle_deposit):
827
        SubTransaction.__init__(self, transaction, amount, item.id, quantity, wholesale)
828
        self.coupon_amount = coupon
829
        self.sales_tax = sales_tax
830
        self.bottle_deposit = bottle_deposit
831
832
833
class RestockLineBox(SubTransaction):
834
    __mapper_args__ = {'polymorphic_identity': 'restocklinebox'}
835
    box_id          = Column(Integer, ForeignKey("boxes.id"), nullable=True)
836
837
    box             = relationship(box.Box, backref="subtransactions")
838
839
    def __init__(self,
840
                 transaction,
841
                 amount,
842
                 box,
843
                 quantity,
844
                 wholesale,
845
                 coupon,
846
                 sales_tax,
847
                 bottle_deposit):
848
        self.transaction_id = transaction.id
849
        self.amount = amount
850
        self.box_id = box.id
851
        self.quantity = quantity
852
        self.wholesale = wholesale
853
        self.coupon_amount = coupon
854
        self.sales_tax = sales_tax
855
        self.bottle_deposit = bottle_deposit
856
857
858
class InventoryLineItem(SubTransaction):
859
    __mapper_args__    = {'polymorphic_identity': 'inventorylineitem'}
860
    quantity_predicted = synonym(SubTransaction.quantity)
861
    quantity_counted   = Column(Integer)
862
863
    def __init__(self, transaction, amount, item, quantity_predicted, quantity_counted, wholesale):
864
        SubTransaction.__init__(self, transaction, amount, item.id, quantity_predicted, wholesale)
865
        self.quantity_counted = quantity_counted
866
867
868
869
################################################################################
870
## SUBSUB TRANSACTIONS
871
################################################################################
872
873
# This is for tracking which items were in which boxes when we restocked
874
875
class SubSubTransaction(Base):
876
    __tablename__      = "subsubtransactions"
877
878
    id                 = Column(Integer, primary_key=True, nullable=False)
879
    subtransaction_id  = Column(Integer, ForeignKey("subtransactions.id"), nullable=False)
880
    type               = Column(Enum("restocklineboxitem",
881
                                     name="subsubtransaction_type"), nullable=False)
882
    item_id            = Column(Integer, ForeignKey("items.id"), nullable=True)
883
    quantity           = Column(Integer, nullable=False)
884
885
    subtransaction     = relationship(SubTransaction, backref="subsubtransactions", cascade="all")
886
    item               = relationship(item.Item, backref="subsubtransactions")
887
888
    __mapper_args__    = {'polymorphic_on': type}
889
890
    def __init__(self, subtransaction, item_id, quantity):
891
        self.subtransaction_id = subtransaction.id
892
        self.item_id = item_id
893
        self.quantity = quantity
894
895
    def __getattr__(self, name):
896
        if name == 'deleted':
897
            return self.subtransaction.transaction.event.deleted
898
        else:
899
            raise AttributeError
900
901
    @classmethod
902
    @limitable_all
903
    def all_item(cls, item_id):
904
        return DBSession.query(cls)\
905
                        .join(SubTransaction)\
906
                        .join(Transaction)\
907
                        .join(event.Event)\
908
                        .filter(cls.item_id == item_id)\
909
                        .filter(event.Event.deleted==False)\
910
                        .order_by(cls.id)
911
912
913
class RestockLineBoxItem(SubSubTransaction):
914
    __mapper_args__ = {'polymorphic_identity': 'restocklineboxitem'}
915
    def __init__(self, subtransaction, item, quantity):
916
        SubSubTransaction.__init__(self, subtransaction, item.id, quantity)
917
918
919
920